本文介绍了序列化一个不实现可序列化的类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现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 an Address type. You can serialize if you call the Employee.setAddress(new SerializableAddress())
  • If Address is null, you can serialize the whole employee even if Address's type is not serializable.
  • If you mark Address as transient, it will skip trying to serialize Address. 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.

这篇关于序列化一个不实现可序列化的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:07
查看更多