简体   繁体   English

在静态Java方法中访问类

[英]Accessing class in static java method

We have self registering subclasses of 'Handler' which we want to access through Subclass.me(). 我们具有要自动通过Subclass.me()访问的“处理程序”子类。 Is something similar to this possible in Java: ? 在Java中是否可能与此类似:

public class Handler{
static Vector<Handler> register=new Vector<Handler>();
public static Handler me() {
        return register.get( this.class);// TODO
}
}

public class SubClass extends Handler{
     SubClass(){register.add(this);}// OK
}

To clarify the question: Is it possible to retrieve the CLASS when calling a static java method? 为了澄清这个问题:调用静态java方法时是否可以检索CLASS? this.class obviously doesn't work, because 'this' is not available. this.class显然不起作用,因为'this'不可用。

Static methods belong to the class. 静态方法属于该类。 They cannot be overridden. 它们不能被覆盖。

MyClass.myStaticMethod()

is the only correct way of accessing a static method. 是访问静态方法的唯一正确方法。

In java, you cannot make a static reference to the non-static method/variable. 在Java中,您不能对非静态方法/变量进行静态引用。 So, 所以,

  • If you want to access a non-static method / variable then you must create an instance of the class first. 如果要访问非静态方法/变量,则必须首先创建该类的实例。
  • If you are going to access a static method / variable then you can access it directly through the class name without creating a instance. 如果要访问静态方法/变量,则可以直接通过类名称访问它,而无需创建实例。

Because, the static method and variable are belong to the Class not to the Instance while the non-static method and variable are belong to the Instance not to the Class. 因为,静态方法和变量属于类而不是实例,而非静态方法和变量属于实例而不是类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM