狗.java
public class Dog extends Animal {
.....
}
<小时/>
动物.java
public class Animal {
public static String getName() {
String callerClassName = ????; //How to get the class Dog, when I call from TestCase
return "Animal";
}
}
当我使用 TestCase 类到 Dog.getName() 时,当我使用 Thread.currentThread().getStackTrace()[1].getClassName() 时如何获取 className Dog 而不是 Animal
public class TestCase {
public static String getName(){
return Dog.getName();
}
}
最佳答案
对于非静态方法,您可以使用 this.getClass()
来获取所调用对象的具体类,但这不适用于静态方法。当您像这样调用继承的静态方法时,根本不涉及子类,因此我认为该信息不可用。
无论如何,这可能是设计问题的迹象。由于静态方法没有动态分派(dispatch),因此要在 Dog
类上调用 getName()
,您必须在源代码中显式引用 Dog
。当您必须知道子类已经才能调用其方法时,拥有返回子类名称的方法没有多大意义。
关于java - 我可以在Java中获取子类名吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571545/