Java:父类可以静态获取子类的类名吗?

标签 java class inheritance static classname

关于Java,我想静态知道当前类的类名。 A是B的父类。我想在A(父类)中有一个静态字符串,其中包含当前类的类名,但是当在B(子类)中引用这个静态字符串时,它应该包含B 的类名。这可能吗?

例子:

public class Parent {

protected static String MY_CLASS_NAME = ???
.
.
.
}

public class Child extends Parent {

public void testMethod() {
     if (MY_CLASS_NAME.equals(getClass().getName())) {
        System.out.println("We're equal!");
     }
}

}

最佳答案

我知道的唯一方法如下: 在父类中创建接受 String 的 protected 构造函数。

class Parent {
    private final String className;
    protected Parent(String className) {
         this.className = className;
    }
}

public class Child extends Parent {
    public Child() {
        super("Child");
    }
}

顺便说一句,您甚至可以在 paren 的 custructor 中使用 new Throwable().getStackTrace() 来改进它。在这种情况下,您甚至不必强制所有 child 将他们的名字传递给 parent 。

class Parent {
    private final String className;
    protected Parent() {
         StackTraceElement[] trace = new Throwable().getStackTrace();
         this.className = trace[1].getClassName();
    }
}

关于Java:父类可以静态获取子类的类名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705607/

相关文章:

java - 使用单选框/复选框实现 JTree 节点

c++ - 基类和派生类 C++

c++ - 错误 : No matching function found

java - Java中的类和对象问题

qt - 子类中是否需要调用基类的事件处理器?

c++ - 如何在 C++ 中将运算符作为函数调用

c++ - 在 C++ 中继承同一个类两次(故意)

java - 如何在不阻塞的情况下从嵌套的 CompletableFuture 返回值?

java - 集群上 weblogic 的 EJB 计时器的替代方案

java - FileInputStream 和 OutputStream 无法在文件中读取和写入对象