考虑这个Java代码Java中,获取Class对象包含类,而不是运行时类
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()
,因为这会给我runtype,这是B
。我正在寻找一种方式来获得class
f()
的Class
对象内(不提A
明确,明显)
你为什么不明确提及A? 'A.class'似乎是最直接的解决方案。 – 2009-10-02 01:27:10
我想如果你必须弄清楚你的实例在运行时的确切类型,就会给出一个强烈的信号,指出需要重构或重新思考。 – aberrant80 2009-10-02 04:04:39