8

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

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
user2047302
  • 81
  • 1
  • 1
  • 3

3 Answers3

6

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.

scraymer
  • 461
  • 7
  • 14
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
1

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

Community
  • 1
  • 1
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
  • Also this class is being used in many others logics. If I have to create a new class that is exactly same I ll have to rewrite so many parts of the app. – user2047302 Sep 05 '13 at 18:20
  • You can simply inherit this class without overriding any of the methods in it. It will be as good as base class. – Ankur Shanbhag Sep 05 '13 at 18:26
0

If you have the option to use a 3rd party library for serialization, then you can use for example kryo. This has a default serialization which doesn't require implementing interfaces or annotating fields.

You can check Which is the best alternative for Java Serialization? for more alternatives.

Community
  • 1
  • 1
Katona
  • 4,816
  • 23
  • 27