简体   繁体   中英

Getting Class reference of Subclass from Superclass

How can I get a reference to a Subclass's Class from a Superclass method?

Eg,

public class MySuper {
  public void myMethod(){
    // here i need a reference to MySub1.class or MySub2.class
    // depending on the class of the instance that invoked this method
  }
}

public class MySub1 extends MySuper {
  public String myString;
}
public class MySub2 extends MySuper {
  public int myInt;
}

Sounds like you just want:

Class<?> clazz = getClass();

Or more explicitly:

Class<?> clazz = this.getClass();

Note that it won't be the class containing the code that invoked the method - it'll be the class of the object that the method was invoked on . If you want the class of the caller, that's a whole different matter.

如果调用getClass()则会获取实例的类。

MySub1 sub1 = new MySub1();
sub1.getClass(); // returns the MySub1.
sub1.getClass().getSuperclass(); // returns MySuper 

I hope this is what you need.

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