Java serialization of non serializable third party class

5.7k Views Asked by At

I am currently developing a web application and I would like to make java objects persistent at the server so that they can be retrieved at any time. Since a database is an overkill for my application, I choose the easiest way of persisting java objects: serialization to xml or to bytes. Unfortunately a big part of the code I use are java classes which I cannot modify and these classes do not implement the interface 'serializable'. What are my options regarding to serializing objects of these classes, as well as other interacting objects of my own classes?

3

There are 3 best solutions below

0
Jeremy Grand On BEST ANSWER

As I said in my comments, I'd go for a SerializationService which would find the proper Serializer<T> for every object you want to save.

Something like :

public interface Serializer<T> {

Serializable toSerializable(T objectToSerialize);

//to build a factory/service around it
boolean canDeserialize(Serializable serializedObject);

T fromSerializable(Serializable serializedObject);

}

And if you want a basic, concrete example : with the quite-common Path :

public class PathSerializer implements Serializer<Path> {

@Override
public Serializable toSerializable(Path objectToSerialize) {
    return objectToSerialize.toString();
}

@Override
public Path fromSerializable(Serializable serializedObject) {
    if(!canDeserialize(serializedObject)){
        throw new IllegalArgumentException("Cannot deserialize this");
    }
    return Paths.get((String)serializedObject);
}

@Override
public boolean canDeserialize(Serializable serializedObject) {
    return serializedObject != null && serializedObject instanceof String;
}

}

You could also very well store POJO containing the name your original object class and the list of parameters needed in its constructor an/or a map of its fields to be able to regenerate your objects by reflection.

It's all up to you and the complexity of your application.

0
mammago On

I think JSON would be the go-to solution here. Take Googles GSON library for example. You don't need to annotate your classes, simply write

Gson gson = new Gson();
MyObj obj = gson.fromJson(jsonString);
String json = gson.toJson(obj);

For more general information about the JSON format see the official JSON documentation.

1
Sagito On

One option would be to extend the classes that you don't have access to, in order to save their internal state, and implement Serializable on those.

More info on this SO question: Serializing a class variable which does not implement serializable

Besides this, I don't think there is any other option except building some wrappers and serializing the classes manually to XML or JSON.