Reputation: 3935
How can I get a reference to a Subclass's Class from a Superclass method?
E.g.,
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;
}
Upvotes: 0
Views: 3242
Reputation: 115388
MySub1 sub1 = new MySub1();
sub1.getClass(); // returns the MySub1.
sub1.getClass().getSuperclass(); // returns MySuper
I hope this is what you need.
Upvotes: 0
Reputation: 1503090
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.
Upvotes: 3