Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

de/serialize java objects across different applications using different package names

I want to share java objects across different applications.

As long as I use the same package names in the different projects it works fine. But if I change the package names it doesn't work anymore.

I tried to solve this by extend the ObjectInputStream class and overriding the readClassDescriptor method.

But by doing so I get the following error:

java.io.StreamCorruptedException: invalid type code: 00

... dont know how to solve this problem.

Here is the code I use for the extended ObjectInputStream class:

public class MyObjectInputStream extends ObjectInputStream {

    public static Map<String, Class> classNameMapping = initclassNameMapping(); 

    private static Map<String, Class> initclassNameMapping(){
        Map<String, Class> res = new HashMap<String, Class>();
        //ipxTest is the name of the package where the objects got serialized
        res.put("ipxTest.IPX", interprojectxchangeTest.IPX.class); 
        res.put("ipxTest.A", interprojectxchangeTest.A.class);
        return Collections.unmodifiableMap(res);
    }

    public MyObjectInputStream(InputStream in) throws IOException {
        super(in);
        enableResolveObject(true);
    }


    protected MyObjectInputStream() throws IOException, SecurityException {
        super();
        enableResolveObject(true);
    }

    @Override
    protected java.io.ObjectStreamClass readClassDescriptor() 
            throws IOException, ClassNotFoundException {
        ObjectStreamClass desc = super.readClassDescriptor();
        if (classNameMapping.containsKey(desc.getName()))
            return ObjectStreamClass.lookup(classNameMapping.get(desc.getName()));
        return desc;
    }
}

The IPX and A classes both look equal in the different projects and have each the same serialID.

like image 263
matthiasboesinger Avatar asked Sep 30 '14 16:09

matthiasboesinger


People also ask

How many ways we can serialize object in Java?

Java Serialization Methods That's why there are four methods that we can provide in the class to change the serialization behavior.

How can we avoid serialization of objects in Java?

There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods.

What is serialization and deserialization explain with example?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.

What is the difference between serializable and Externalizable interface in Java?

Serializable interface passes the responsibility of serialization to JVM and the programmer has no control over serialization, and it is a default algorithm. The externalizable interface provides all serialization responsibilities to a programmer and hence JVM has no control over serialization.


1 Answers

My first suggestion is to make your implementation simple and stop fighting the framework - use the same package names across applications. I would suggest making a library out of the serializable classes, and sharing that among the implementations.

If you MUST serialize / deserialize across applications with different package names, then my suggestion would be to forego the built-in Java serialization, which is tightly tied to the class name and package name, and use something like Gson to serialize / deserialize.

Gson allows you to specify a TypeAdaper. You can create and register a TypeAdapter for each class that you will serialize/deserialize, and specify the class name (without the package name) as the 'type' when serializing, like the following example, but use getSimpleName() instead of getCanonicalName()

When deserializing, you'd have to add the correct package name to the "type"

You'd have to do the TypeAdapters individually for each application.

public class GsonTypeAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
    @Override
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("type", new JsonPrimitive(src.getClass().getCanonicalName()));
        result.add("properties", context.serialize(src, src.getClass()));

        return result;
    }

    @Override
    public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get("type").getAsString();
        JsonElement element = jsonObject.get("properties");

        try {
            return context.deserialize(element, Class.forName(type));
        } catch (ClassNotFoundException cnfe) {
            throw new JsonParseException("Unknown element type: " + type, cnfe);
        }
    }
}
like image 148
GreyBeardedGeek Avatar answered Oct 05 '22 11:10

GreyBeardedGeek