Search code examples
javaserializationserializable

JAVA: is it possible to serialize a 3rd party class non serializable with private fields?


Im trying to create an intermediate serializable class in order to copy the fields but i cant because those fields are private, any suggestion?

public class RowSerializable extends Row implements Serializable{

    public Object[] fields;

    public RowSerializable(int arity, Row a) {
        super(arity);
        this.fields = a.fields;
    }
}

The problem is that the Row type fields is private private final Object[] fields;


Solution

  • You can use reflection in order to acquire the values of all fields from your superclass; see here for guidance on that.

    You could then store that information in your derived class; and then you should be able to serialize objects of your new class.

    The ugly thing of course: upon de-serialization, you also have to use reflection to push all the field values of RowSerializable back into the Row parent fields.

    All of that might be technically doable, but of course, that is not a very robust solution. Example: when a new version of that Row class is used, that might not work at all with Row instances that were previously serialized with older versions of Row.class.

    Thus, my personal two cent: be really careful about doing that. It feels like a dirty hack that definitely does not come for free.

    Update: I think in order to get things working you can't even use inheritance here - as serialization walks the whole inheritance tree. So you probably have to drop that "extends Row" from your code in the first place.