以下代码:
public class A {
Class klass;
T instance;
public A(T instance) {
this.klass = instance.getClass(); // this requires an explicit cast to Class to satisfy the compiler
this.instance = instance;
}
}
汇编:
A.java:7: error: incompatible types
this.klass = instance.getClass();
^
required: Class
found: Class
where T is a type-variable:
T extends Object declared in class A
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ? extends Object
1 error
为什么编译器不满足instance.getClass()将始终生成Class< T> (因为实例是T类型)并且需要显式转换?我安全只是添加显式转换:
this.klass = (Class) instance.getClass();
…从而使编译器静音或者是否存在运行时意外的空间?如果没有,为什么编译器不能解决这个问题呢?