Serializing a class variable that does not implement serializable

I have a class that implements Serializable. There is another class object in the class that does not implement serializable. What you need to do to serialize a member of the class.

My class is something like this

public class Employee implements Serializable{ private String name; private Address address; } public class Address{ private String street; private String area; private String city; } 

Here I do not have access to the Address class to implement Serializable. Please help. thanks in advance

+6
source share
3 answers

Well, of course, there is an obvious decision to put Serializable on it. I understand that this is not always an option.

Perhaps you can extend Address and put Serializable on the child you created. Then make Employee have a Child field instead of an Address field.

Here are a few more things to keep in mind:

  • You can save the Employee.address field as the Address type. You can serialize if you call Employee.setAddress(new SerializableAddress())
  • If Address is null, you can serialize the entire employee, even if the Address 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 “serializations,” such as XStream , which do not require the marker interface to work. It depends on your requirements, be it an option.

+3
source

You yourself create this address class with a serializable class, because you do not have access to change it.

There are several options:

  • Subclass the Address class and use it. You can mark this class as serializable.
  • Mark the address as temporary.

Please check out this fooobar.com/questions/105131 / ... link

+1
source

If you have the opportunity to use a third-party library for serialization, you can use, for example, kryo . This has default serialization, which does not require implementation of interfaces or annotation of fields.

Can you check what is the best alternative for Java Serialization? for more alternatives.

0
source

Source: https://habr.com/ru/post/953265/


All Articles