参考
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的受保护的构造函数.
创建在父类中接受String的受保护的构造函数.
class Parent {
private final String className;
protected Parent(String className) {
this.className = className;
}
}
public class Child extends Parent {
public Child() {
super("Child");
}
}
BTW你甚至可以使用新的Throwable().在括号的构造函数中获取getStackTrace().在这种情况下,您甚至不必强制所有的孩子将他们的名字传给父母.
class Parent {
private final String className;
protected Parent() {
StackTraceElement[] trace = new Throwable().getStackTrace();
this.className = trace[1].getClassName();
}
}