1

I have got an object which contains non serializable object inside.

class object BigObject<T extends smallObject> implements Serializable{
private T insideObject;
public BigObject(T insideObject) {this.insideObject = insideObject;}
}

I would like to serializable Big object, but I get java.io.NotSerializableException error for obvious reasons. I read topics like:Java Serialization with non serializable parts or https://dzone.com/articles/serializing-java-objects-non The answers were very interesting, but could not resovle my problem. First of all insideObject is a class from a library, co I cannot add serializable implementation. The answer given on the dzone webpage is also interesting (to write your own writeObject methods). But as you can see, insideObject is a generic class, we can get a few types of insideObject extending on smallObject in bigObject, so this solution is impossible.

So, is it possible to manage with this problem in the other way? Maybe I can somehow add implementation of serializable on the existing object? Or only external liblaries as Kyro can help me with my problem?

Community
  • 1
  • 1
Thamiar
  • 600
  • 7
  • 22

4 Answers4

0

You should try to implement Externalizable Interface rather than Serializable

Then you need to override the writeExternal and readExternal method of Externalizable

public void writeExternal(ObjectOutput out) throws IOException  {
    out.writeObject(urObject);
    }
Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
0

This is why java has Transient keyword right? Declare the variable which is non serializable as transient and your problem will be solved. i.e. private transient T insideObject;

0

Use transient before any field that you don't want to be incorporated into a serialisation.

Standard serialisers will pass over that field.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

I think the example from dzone is something that can help you.

One approach is to use BigObject as an abstract base class and create subclasses for each case of smallObject that handles their own serialization/desearialization logic following the example you posted.

The other is sticking to a single BigObject class, but, during the serialization you can also serialize the class name of the concrete smallObject instance. Then during deserialization, you can modify the logic accordingly.

private void writeObject(final ObjectOutputStream out) throws IOException {
    out.writeUTF(this.insideObject.getClass().getCanonicalName());
    // serialize this.insideObject
}

private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    String insideClassName = in.readUTF();
    // choose logic based on class name
}

I would personally go with the first approach, since it will keep the code cleaner and stick to OOP best practices.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28