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

前端 未结 12 2250
滥情空心
滥情空心 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 06:00

    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.

提交回复
热议问题