2016-06-13 39 views
2

我试着明白getClass方法返回的原因是什么Class<? extends |X|>为什么getClass返回一个Class <?扩展| X |>?

openjdk邻近public final native Class<?> getClass();

实际结果类型是Class<? extends |X|> 其中|X|是静态类型的 表达在其上getClass被称为的擦除。

为什么不能getClass有相同的类型,如XClass.class,例如:

class Foo {} 
Foo fooInstance = new Foo(); 
Class<Foo> fc = Foo.class; // Works! 
Class<Foo> fc2 = fooInstance.getClass(); // Type mismatch ;(
Class<?> fc3 = fooInstance.getClass(); // Works! 
Class<? extends Foo> fc4 = fooInstance.getClass(); // Works! 
+0

相关:HTTP:// stackoverflow.com/questions/19332856/what-is-meant-by-the-erasure-of-the-static-type-of-the-expression-on-which-it-i和http://stackoverflow.com/问题/ 18144556/java-getclass-bound-type – Tunaki

回答

5
Foo foo = new SubFoo(); 

你期望foo.getClass()返回? (它将返回SubFoo.class。)

这是整个问题的一部分:getClass()返回实际对象的类,而不是引用类型。否则,你可以只写参考类型,并且foo.getClass()Foo.class永远不会有任何区别,所以你只需编写第二个参考类型。

(注意,顺便说一句,这实际上getClass()在类型系统自身的特殊处理,而不是像任何其他方法,因为SubFoo.getClass()不返回的Foo.getClass()亚型)

+0

Louis,谢谢你,我想我终于明白了。 –

相关问题