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
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
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