Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a class variable which does not implement 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.

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 dont have access to the Address class to make it implement Serializable. Please help. Thanks in advance

like image 671
user2047302 Avatar asked Sep 05 '13 18:09

user2047302


People also ask

Which variable will not be serialized?

The Transient variable is a variable whose value is not serialized during the serialization process. We will get a default value for this variable when we deserialize it.

How do you prevent a variable from being serialized in a serializable class?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.

What happens if we do not implement serializable?

The Student would not be Serializable, and it will act like a normal class. Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.


2 Answers

Well of course there's the obvious solution to put Serializable on it. I understand that's not always an option.

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:

  • 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.

like image 194
Daniel Kaplan Avatar answered Oct 21 '22 11:10

Daniel Kaplan


You caanot directly make this Address class serializable as you do not have access to modify it.

There are few options :

  • Create a subclass of Address class and use it. You can mark this class as serializable.
  • Mark the Address as transient.

Please take a look at this stackoverflow link

like image 26
Ankur Shanbhag Avatar answered Oct 21 '22 12:10

Ankur Shanbhag