class A {
}
class B extends A {
}
class TestType {
public static void main(String args[]) {
A a = new B();
// I wish to use reference 'a' to check the Reference-Type which is 'A'.
}
}这是可能的吗?如果没有,请说明原因。
发布于 2012-10-03 15:06:14
如果您调用a.getClass(),那么它将始终返回创建此对象的类的实例。在本例中,它是B,因此它将返回B.class。
现在,如果你想在a上调用方法,并以A.class的形式获取类,那么你就不能用正常的方式来做了。
一种解决办法是在A中定义方法
public static Class<A> getType() {
return A.class;
}然后你可以调用A.class的a.getType()。我们在这里使用静态方法,因为它们没有被覆盖。
发布于 2012-10-03 15:15:32
Chris Jester-Young's comment非常优秀。上面写着:
不能。局部变量的静态类型不会保留在字节码中,也不会在运行时保留。(如果它是一个字段,您可以在字段的包含类上使用反射来获取字段的类型。)
另请参阅What is the concept of erasure in generics in Java?
和http://gafter.blogspot.com/search?q=super+type+token。
发布于 2012-10-03 16:01:43
检查Java语言中持有对象的引用的类名
你不能这么做。
https://stackoverflow.com/questions/12703285
复制相似问题