Java泛型:为什么编译器不能告诉这个Class 对象与这个类'type参数的对象的类有相同的类型?

时间:2021-12-31 21:31:53

Why do I need to cast the return of obj.getClass() to a Class<T> type when obj has type T? This also generates a warning, which I have silenced. But I feel like this shouldn't be necessary. What's going on here?

当obj具有类型T时,为什么我需要将obj.getClass()的返回强制转换为Class 类型?这也会产生警告,我已经沉默了。但我觉得这不应该是必要的。这里发生了什么?

public class DataSerialization<T> {
    private T deserializedObject;
    private Class<T> classObject;
    private String serializedObject = null;

    private static final Gson gson = new Gson();

    @SuppressWarnings("unchecked")
    public DataSerialization(T obj) {
        this.deserializedObject = obj;
        this.classObject = (Class<T>) obj.getClass();
    }

    // ...
}   

1 个解决方案

#1


-1  

Simply put, it's because the getClass method returns Class<?>, no matter what type of class the object actually is. Even though the reference of type Class<?> is, in this instance, pointing to an object of type Class<T>, the method signature defines the return type as Class<?>, so that is what the compiler is expecting back.

简单地说,这是因为getClass方法返回Class ,无论对象实际上是什么类型的类。即使类型为Class 的引用在本例中指向类型为Class 的对象,方法签名也将返回类型定义为Class ,这就是编译器期待的内容。

To the compiler, you are casting a Class<?> to a Class<T>, and that flags a warning because there is no way to ensure, by return type alone, that this is the case.

对于编译器,您将一个Class 转换为Class ,并标记一个警告,因为无法单独通过返回类型确保这种情况。

#1


-1  

Simply put, it's because the getClass method returns Class<?>, no matter what type of class the object actually is. Even though the reference of type Class<?> is, in this instance, pointing to an object of type Class<T>, the method signature defines the return type as Class<?>, so that is what the compiler is expecting back.

简单地说,这是因为getClass方法返回Class ,无论对象实际上是什么类型的类。即使类型为Class 的引用在本例中指向类型为Class 的对象,方法签名也将返回类型定义为Class ,这就是编译器期待的内容。

To the compiler, you are casting a Class<?> to a Class<T>, and that flags a warning because there is no way to ensure, by return type alone, that this is the case.

对于编译器,您将一个Class 转换为Class ,并标记一个警告,因为无法单独通过返回类型确保这种情况。