Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 477
Matt Huggins Avatar asked Aug 05 '10 18:08

Matt Huggins


People also ask

How do you find the class name for a subclass?

The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.

Can methods of subclass be accessed by the super class?

Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.

Can methods of sub class be accessed by the super class in Java?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

How do you define a subclass from a superclass?

Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.


2 Answers

Don't make the method static. The issue is that when you invoke getClass() you are calling the method in the super class - static methods are not inherited. In addition, you are basically name-shadowing Object.getClass(), which is confusing.

If you need to log the classname within the superclass, use

return this.getClass().getName(); 

This will return "Entity" when you have an Entity instance, "User" when you have a User instance, etc.

like image 139
matt b Avatar answered Oct 08 '22 16:10

matt b


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?

like image 20
Michael Borgwardt Avatar answered Oct 08 '22 17:10

Michael Borgwardt