+-

我试着理解getClass方法返回Class< ;?的原因是什么?扩展| X |>?
从openjdk附近公共最终本地班级<?>的getClass();:
The actual result type is
Class<? extends |X|>
where|X|is the erasure of the static type of the
expression on whichgetClassis called.
为什么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!
最佳答案
Foo foo = new SubFoo();
你期望foo.getClass()返回什么? (它将返回SubFoo.class.)
这是整点的一部分:getClass()返回真实对象的类,而不是引用类型.否则,您可以只编写引用类型,并且foo.getClass()永远不会与Foo.class有任何不同,所以你只需编写第二个.
(顺便说一句,getClass()实际上在类型系统中有自己的特殊处理,而不像任何其他方法,因为SubFoo.getClass()不返回Foo.getClass()的子类型.)
点击查看更多相关文章
转载注明原文:java – 为什么getClass返回一个Class <?延伸| X |>? - 乐贴网