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

前端 未结 12 2244
滥情空心
滥情空心 2020-12-14 05:31

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         


        
相关标签:
12条回答
  • 2020-12-14 05:45

    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?

    0 讨论(0)
  • 2020-12-14 05:45

    This works for me

    this.getClass().asSubclass(this.getClass())
    

    But I'm not sure how it works though.

    0 讨论(0)
  • 2020-12-14 05:49

    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:

    • Use the existing getClass() method.
    • Pass an argument to your static getClass() method, and call an instance method on that object.
    • Make your method non-static, and rename it.
    0 讨论(0)
  • 2020-12-14 05:50

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

    0 讨论(0)
  • 2020-12-14 05:50

    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();
       }
    }
    
    0 讨论(0)
  • 2020-12-14 05:55

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题