[英]How to serialize a list of type X, filled with objects of type Y, which extends X, and still get Y elements upon deserialization?
I have this list 我有这个清单
LinkedList<ASD> list = new LinkedList<ASD>();
then, I add some objects which extend ASD 然后,我添加一些扩展ASD的对象
BSD bsd = new BSD(); // BSD extends ASD
list.add(bsd);
and serialize list. 并序列化列表。
How can I get it to serialize and deserialize teh bsd element as BSD and not as ASD? 我怎样才能将它作为BSD序列化和反序列化为bhd元素而不是ASD?
It is not a problem. 这不成问题。 All objects that you want to serialize must be instances of classes that implement
Serializable
. 要序列化的所有对象必须是实现
Serializable
的类的实例。 LinkedList
does it. LinkedList
做到了。 Declare either ASD
or BSD
(it does not matter in your case) to implement Serializable
and try. 声明
ASD
或BSD
(在您的情况下无关紧要)来实现Serializable
并尝试。 Everything should work. 一切都应该有效。
As noted by AlexR, everything is fine: 正如AlexR所说,一切都很好:
class ASD implements Serializable {
private static final long serialVersionUID = 1L;
}
class BSD extends ASD {
private static final long serialVersionUID = 1L;
}
LinkedList<ASD> list = new LinkedList<ASD>();
list.add(new BSD())
Now, if you serialize list
, and later deserialize it, its elements will be of the correct type BSD
. 现在,如果你序列化
list
,然后反序列化它,它的元素将是正确的BSD
类型。
Furthermore, the generic type argument (the <ASD>
thing) is not saved during the serialization. 此外,在序列化期间不保存泛型类型参数(
<ASD>
事物)。 The serialization procedure will only remember that list
is a LinkedList
object. 序列化过程只会记住
list
是LinkedList
对象。 What this means is that you can serialize an object of type LinkedList<ASD>
and then deserialize it as LinkedList<BSD>
(or even as eg LinkedList<Integer>
). 这意味着您可以序列化
LinkedList<ASD>
类型的对象,然后将其反序列化为LinkedList<BSD>
(或甚至例如LinkedList<Integer>
)。 An exception can be thrown later, though, if you try to access an element of the list that cannot be cast to the newly specified generic type. 但是,如果您尝试访问无法转换为新指定的泛型类型的列表元素,则可以稍后抛出异常。
Finally, I'm just saying this is doable, not that it is a good practice :) 最后,我只是说这是可行的,而不是这是一个很好的做法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.