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 String getClass() {
return Entity.class.getClass();
}
}
Now I have another class extend that.
class User extends Entity {
}
I want to get the class name of User:
System.out.println(User.getClass());
My goal is to see "com.packagename.User" output to the console, but instead I'm going to end up with "com.packagename.Entity" since the Entity class is being referenced directly from the static method.
If this wasn't a static method, this could easily be solved by using the this
keyword within the Entity
class (i.e.: return this.class.getClass()
). However, I need this method to remain static. Any suggestions on how to approach this?
Why do you want to implement your own getClass() method? You can just use
Edit (to elaborate a bit): You want the method to be static. In that case you must call the method on the class whose class name you want, be it the sub-class or the super-class. Then instead of calling
MyClass.getClass()
, you can just callMyClass.class
orMyClass.class.getName()
.Also, you are creating a
static
method with the same signature as theObject.getClass()
instance method, which won't compile.Each time the extended class is instantiated, its name will be stored in the String and accessible with the getter.
Your question is ambiguous but as far as I can tell you want to know the current class from a static method. The fact that classes inherit from each other is irrelevant but for the sake of the discussion I implemented it this way as well.
it is very simple done by
User.getClass().getSuperclass()
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:
This works for me
But I'm not sure how it works though.