关于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/