Matt Huggins Matt Huggins - 1 year ago 56
Java Question

Getting the name of a sub-class from within a super-class

Let's say I have a base class named

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


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
keyword within the
class (i.e.:
return this.class.getClass()
). However, I need this method to remain static. Any suggestions on how to approach this?

Answer Source

Not possible. Static methods are not runtime polymorphic in any way. It's absolutely impossible to distinguish these cases:


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?