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

一世执手 提交于 2019-12-01 18:24:05

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);
        }
    }
}

The Package name of the class is a fundamental part of its full name.

if matthiasboesinger is ur name then matthias is just ur first name to identify you, but boesinger part is sort of your unique name identifier.

similarly, in classes, the compiler identifies the class and their serialized objects with their complete name and not just the first name.

in case u change the package names, u lose the integrity of the class as different classes can exist in different packages with same name.

so what u are trying is not possible.

unless you write a adapter class which picks up data from the original class with package name and pumps the data into ur new package name class.

but thats just beating around the bush.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!