如果我从泛型 class 派生出非泛型 class,类型会发生什么变化?
What happens to type if I derive non-generic class from a generic class?
比方说,我有一个名为 Person
的普通 POJO。现在,由于类型擦除,ArrayList<Person>
的实例在运行时将具有类型 ArrayList
。如果这个实例通过像 Gson 这样的库经历 serialization/deserialization,反序列化的对象就不是 ArrayList<Person>
,当然,除非我们专门提供一个类型标记。
现在,问题来了。如果我如下创建另一个 class(例如 Persons
)会发生什么:
public class Persons extends ArrayList<Person> {
}
这里会保留类型信息吗?反序列化机制是否能够推断类型确实是 ArrayList<Person>
而不是原始类型 ArrayList
?
Will the type information be preserved here?
是;例如,这个:
final ParameterizedType superTypeOfPersons =
(ParameterizedType) Persons.class.getGenericSuperclass();
System.out.println(superTypeOfPersons.getActualTypeArguments()[0].getSimpleName());
将打印 Person
.
Is deserialization mechanism able to infer that the type is indeed ArrayList<Person>
and not raw type ArrayList
?
它可能可以这样做,但这并不一定意味着它会这样做;这不是一件小事。如果您需要支持一组特定的序列化框架,那么您应该对每个框架进行测试。
比方说,我有一个名为 Person
的普通 POJO。现在,由于类型擦除,ArrayList<Person>
的实例在运行时将具有类型 ArrayList
。如果这个实例通过像 Gson 这样的库经历 serialization/deserialization,反序列化的对象就不是 ArrayList<Person>
,当然,除非我们专门提供一个类型标记。
现在,问题来了。如果我如下创建另一个 class(例如 Persons
)会发生什么:
public class Persons extends ArrayList<Person> {
}
这里会保留类型信息吗?反序列化机制是否能够推断类型确实是 ArrayList<Person>
而不是原始类型 ArrayList
?
Will the type information be preserved here?
是;例如,这个:
final ParameterizedType superTypeOfPersons =
(ParameterizedType) Persons.class.getGenericSuperclass();
System.out.println(superTypeOfPersons.getActualTypeArguments()[0].getSimpleName());
将打印 Person
.
Is deserialization mechanism able to infer that the type is indeed
ArrayList<Person>
and not raw typeArrayList
?
它可能可以这样做,但这并不一定意味着它会这样做;这不是一件小事。如果您需要支持一组特定的序列化框架,那么您应该对每个框架进行测试。