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

前端 未结 12 2258
滥情空心
滥情空心 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: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...

提交回复
热议问题