Let\'s say I have a base class named Entity
. In that class, I have a static method to retrieve the class name:
class Entity {
public static
Not possible. Static methods are not runtime polymorphic in any way. It's absolutely impossible to distinguish these cases:
System.out.println(Entity.getClass());
System.out.println(User.getClass());
They compile to the same byte code (assuming that the method is defined in Entity
).
Besides, how would you call this method in a way where it would make sense for it to be polymorphic?
This works for me
this.getClass().asSubclass(this.getClass())
But I'm not sure how it works though.
A static method is associated with a class, not with a specific object.
Consider how this would work if there were multiple subclasses -- e.g., Administrator is also an Entity. How would your static Entity method, associated only with the Entity class, know which subclass you wanted?
You could:
If I understand your question correctly, I think the only way you can achieve what you want is to re-implement the static method in each subclass, for example:
class Entity {
public static String getMyClass() {
return Entity.class.getName();
}
}
class Derived extends Entity {
public static String getMyClass() {
return Derived.class.getName();
}
}
This will print package.Entity and package.Derived as you require. Messy but hey, if those are your constraints...
My context: superclass Entity with subclasses for XML objects. My solution: Create a class variable in the superclass
Class<?> claz;
Then in the subclass I would set the variable of the superclass in the constructor
public class SubClass {
public SubClass() {
claz = this.getClass();
}
}
If i am taking it right you want to use your sub class in base class in static method I think you can do this by passing a class parameter to the method
class Entity {
public static void useClass(Class c) {
System.out.println(c);
// to do code here
}
}
class User extends Entity {
}
class main{
public static void main(String[] args){
Entity.useClass(Entity.class);
}
}