为什么泛型实例的 class 和泛型 class 不一样?

Why is the class of instance of generic type not the same as the generic type class?

编辑:更简单的例子:

public <T> void shouldBeAbleToGetClassOfT(T t) {
    Class<T> tClass;

    // OK, but shows "unchecked cast" warrning.
    tClass = (Class<T>) t.getClass();

    // Compilation error!
    tClass = t.getClass();
}

Incompatible types.

Required: Class<T>

Found: Class<capture<? extends java.lang.Object>>

我对下面示例中的类型擦除有点困惑:

public static class Example<T> {
    private final T t;

    public Example(final T t) {
        this.t = t;
    }

    public <U extends T> void test(Consumer<T> consumer, U u) {
        // OK, but shows "unchecked cast" warrning.
        consumer.accept((T) t.getClass().cast(u));

        // OK, but shows "unchecked cast" warrning.
        consumer.accept(((Class<T>)t.getClass()).cast(u));

        // Compilation error!
        consumer.accept(t.getClass().cast(u));
    }
}

有问题的错误是:

Error:(21, 46) java: incompatible types: java.lang.Object cannot be converted to T

这里到底发生了什么?

.getClass() return 值是否被删除?为什么?

处理此错误的最佳方法是什么?


编辑:这是一个更复杂的用例,与我的问题更密切相关:

public class A<T> {
    private final T t;

    public A(final T t) {
        this.t = t;
    }

    public void printClass() {
        // OK, but shows "unchecked cast" warrning.
        B<T> b = new B<>((Class<T>) t.getClass());

        // Compilation error!
        B<T> b = new B<T>(t.getClass());

        b.printClass();
    }
}

public class B<T> {
    private final Class<T> t;

    public B(final Class<T> t) {
        this.t = t;
    }

    public void printClass() {
        System.out.println(t);
    }
}

来自 getClass 的文档:

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.

t的静态类型是T,擦除是Object。这意味着 t.getClass() 具有静态类型 Class<? extends Object>,而不是您可能期望的 Class<? extends T>

因为t.getClass()有静态类型Class<? extends Object>,编译器只知道t.getClass().cast(u)是一个Object,而不是T。这意味着你不能将它传递给 consumer.accept.