考虑这段 Java 代码
class A{
//@returns Class object this method is contained in
// should be A in this case
public Class<?> f() {
return getClass();
}
}
class B extends A {}
B b = new B();
System.out.println(b.f());
//output -- B.class (Wrong, should be A.class)
在 f()
中,我不能使用 getClass()
,因为它会给我运行类型,即 B
。我正在寻找一种方法来获取 class
f()
的 Class
对象在里面(没有提到 A
明确地,显然地)
最佳答案
new Object() {}.getClass().getEnclosingClass()
。但请不要!
关于Java,获取包含类的类对象,而不是运行时类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1507257/