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

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

    Your question is ambiguous but as far as I can tell you want to know the current class from a static method. The fact that classes inherit from each other is irrelevant but for the sake of the discussion I implemented it this way as well.

    class Parent {
        public static void printClass() {
          System.out.println(Thread.currentThread().getStackTrace()[2].getClassName());
        }
    }
    
    public class Test extends Parent {
        public static void main(String[] args) {
          printClass();
        }
    }
    

提交回复
热议问题