问题描述
我有一个实现Serializable的类。类中有一个其他类对象,它不实现可序列化。应该怎么做才能序列化该类的成员。
I have a class which implements Serializable. There is an other class object in the class which does not implement serializable. What should be done to serialize the member of the class.
我的类是这样的
public class Employee implements Serializable{
private String name;
private Address address;
}
public class Address{
private String street;
private String area;
private String city;
}
在这里,我没有访问Address类来实现Serializable。请帮忙。在此先感谢
Here, I dont have access to the Address class to make it implement Serializable. Please help. Thanks in advance
推荐答案
当然,显而易见的解决方案是放置 Serializable
就可以了。我知道这并不总是一个选项。
Well of course there's the obvious solution to put Serializable
on it. I understand that's not always an option.
也许你可以扩展地址
并放入您所制作的孩子可序列化
。然后你这样做员工
有一个 Child
字段而不是地址
字段。
Perhaps you can extend the Address
and put Serializable
on the child you make. Then you make it so Employee
has a Child
field instead of an Address
field.
以下是一些需要考虑的事项:
Here are some other things to consider:
- 你可以将
Employee.address
字段保存为地址
类型。如果你调用Employee.setAddress(new SerializableAddress())
- 如果
地址
为null,即使地址
的类型不可序列化,也可以序列化整个员工。 - 如果你将
地址
标记为瞬态,它将跳过尝试序列化地址
。这可以解决您的问题。
- You can keep the
Employee.address
field as anAddress
type. You can serialize if you call theEmployee.setAddress(new SerializableAddress())
- If
Address
is null, you can serialize the whole employee even ifAddress
's type is not serializable. - If you mark
Address
as transient, it will skip trying to serializeAddress
. This may solve your problem.
然后还有其他序列化框架,如,不需要标记接口工作。这取决于您的要求是否是一个选项。
Then there are other "serialization" frameworks like XStream that don't require the marker interface to work. It depends on your requirements whether that's an option though.
这篇关于序列化一个不实现可序列化的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!