Incompatible types: class <T> found: class <CAP # 1>, where T is a type variable

The following code:

public class A<T> {

    Class<T> klass;
    T instance;

    public A(T instance) {
        this.klass = instance.getClass(); // this requires an explicit cast to Class<T> to satisfy the compiler
        this.instance = instance;
    }
}

gives at compilation:

A.java:7: error: incompatible types
             this.klass = instance.getClass();
                                           ^
required: Class<T>
found:    Class<CAP#1>
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

Why is the compiler not satisfied with what instance.getClass()it will always create Class<T>(since it instancehas a type T) and requires an explicit conversion instead? I'm sure just adding an explicit cast:

this.klass = (Class<T>) instance.getClass();

... and thus silence the compiler or is there room for surprises at runtime? And if not, why can't the compiler understand this?

+4
source share
1 answer

, .getClass() ( T) ?

:

A<Object> a = new A<Object>("Foo");

instance.getClass() a Class<Object> - a Class<String>. , String Object.

:

Class<? extends T> klass;

, , Object.getClass() Class<? extends |T|> ( JLS 4.3. 2):

getClass - Class<? extends |T|>, T - , (§15.12.1) getClass.

|T| T, Object.

, , @SuppressWarnings("unchecked"), , .

+10

All Articles