[英]Why does getClass return a Class<? extends |X|>?
I tried to understand what is the reason for getClass
method to return Class<? extends |X|>
我试着理解
getClass
方法返回Class<? extends |X|>
的原因是什么Class<? extends |X|>
Class<? extends |X|>
? Class<? extends |X|>
?
From the openjdk near public final native Class<?> getClass();
从openjdk附近
public final native Class<?> getClass();
: :
The actual result type is
Class<? extends |X|>
实际的结果类型是
Class<? extends |X|>
Class<? extends |X|>
where|X|
Class<? extends |X|>
where|X|
is the erasure of the static type of the expression on whichgetClass
is called.是调用
getClass
的表达式的静态类型的擦除。
Why can't getClass
have the same type such as XClass.class
, for example: 为什么
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();
What do you expect foo.getClass()
to return? 你期望
foo.getClass()
返回什么? (It's going to return SubFoo.class
.) (它将返回
SubFoo.class
。)
That's part of the whole point: that getClass()
returns the class of the real object, not the reference type. 这是整点的一部分:
getClass()
返回真实对象的类,而不是引用类型。 Otherwise, you could just write the reference type, and foo.getClass()
would never be any different from Foo.class
, so you'd just write the second one anyway. 否则,您可以只编写引用类型,并且
foo.getClass()
永远不会与Foo.class
有任何不同,所以你只需编写第二个。
(Note, by the way, that getClass()
actually has its own special treatment in the type system, not like any other method, because SubFoo.getClass()
does not return a subtype of Foo.getClass()
.) (顺便说一句,
getClass()
实际上在类型系统中有自己的特殊处理,而不像任何其他方法,因为SubFoo.getClass()
不返回Foo.getClass()
的子类型。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.