简体   繁体   中英

Accessing class in static java method

We have self registering subclasses of 'Handler' which we want to access through Subclass.me(). Is something similar to this possible in 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? this.class obviously doesn't work, because 'this' is not available.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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