Java泛型:为什么someObject.getClass()不返回Class< ;?延伸T> [英] Java generics: why someObject.getClass() doesn't return Class<? extends T>?
问题描述
我期望从编译时间方面以及从运行时方面来看, .getClass()
不会提供正确的问题
但是我一定错了。
public class _GetClassGenerics2 {
static class MyClass {
}
public static void main(String [] args){
MyClass myInstance = new MyClass );
//这里工作
class< ;? extends MyClass> type = myInstance.getClass();
myMethod(myInstance);
}
public static< T extends MyClass> void myMethod(T instance){
Class< ;?延伸T> type = instance.getClass();
// java.lang.RuntimeException:不可编译的源代码 - 不兼容的类型
//必需:java.lang.Class< ;?延伸T>
// found:java.lang.Class< capture#1 of? extends _GetClassGenerics2.MyClass>
}
}
strong>它不能使用类< T>
和类< ;? oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()rel =nofollow>
getClass
方法的Javadoc :
实际的结果类型是
Class< ;?
其中| X |是调用
extends | X |>getClass
的表达式
的静态类型的擦除
。对于
示例,在此
代码片段中不需要转换
您的代码片段中的$ c> | X | 是 MyClass
,因此 instance.getClass()
只能分配给 Class< ;?扩展MyClass>
或类<?>
。
措辞是因为当你说对于具有< T extends MyClass>
的类型T的变量,可以有多个扩展 MyClass
,因此能够满足
T extends MyClass
条件。没有运行时信息,没有办法知道在方法中是否传递了 MyClass
的具体实现子类。因此,为了提供通用解决方案,它返回< ;?扩展MyClass>
,因为对于 MyClass
的任何子类都是如此。
I would expect that from the aspect of compile time as well as from the aspect of runtime it wouldn't be a problem for .getClass()
to provide a correctly-typed return value.
But I must be wrong.
public class _GetClassGenerics2 {
static class MyClass {
}
public static void main(String[] args) {
MyClass myInstance = new MyClass();
// here it works
Class<? extends MyClass> type = myInstance.getClass();
myMethod(myInstance);
}
public static <T extends MyClass> void myMethod(T instance) {
Class<? extends T> type = instance.getClass();
// java.lang.RuntimeException: Uncompilable source code - incompatible types
// required: java.lang.Class<? extends T>
// found: java.lang.Class<capture#1 of ? extends _GetClassGenerics2.MyClass>
}
}
EDIT: It doesn't work with Class<T>
and Class<? super T>
either.
As per the Javadoc of the getClass
method:
The actual result type is
Class<? extends |X|>
where |X| is the erasure of the static type of the expression on whichgetClass
is called. For example, no cast is required in this code fragment
Here, the value for |X|
in your code snippet is MyClass
, hence instance.getClass()
is assignable to only Class<? extends MyClass>
or Class<?>
.
The reason for this specific wording is because when you say that for this variable having type T where <T extends MyClass>
, there can be multiple classes which extend MyClass
and hence capable of satisfying the T extends MyClass
criteria. Without runtime information there is no way of knowing which concrete implementation subclass of MyClass
was passed in the method. Hence to provide a generic solution, it returns <? extends MyClass>
since that would hold true for any subclass of MyClass
irrespective of what class instance is passed in.
这篇关于Java泛型:为什么someObject.getClass()不返回Class< ;?延伸T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!