How can I change package for a bunch of java serializable classes

丶灬走出姿态 提交于 2021-02-17 20:51:19

问题


I want to change the packages of multiple classes in my application. A nice eclipse redactor good have been great but some of my classes are Serializables and I need to support cross version compatibility.

Any Idea on how it can be done? Can it be done automatically/semi-automatically?


回答1:


If the class structure remains the same, you can subclass a custom ObjectInputStream, call enableResolveObject(true) in its constructor and then override readClassDescriptor() with something like that:

protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
    ObjectStreamClass read = super.readClassDescriptor();
    if (read.getName().startsWith("com.old.package.")) {
        return ObjectStreamClass.lookup(Class.forName(read.getName().replace("com.old.package.", "org.new.package.")));
    }
    return read;
}



回答2:


You simply can't change neither the name of your class nor your package without breaking the compatibility with the Serialization.

You'll have to find a way to keep your classes in the same package or you have to break the retro-compatibility.

If you still do updates on previous versions of your application, you can create a mandatory update which will change the way you serialize your data and go without the default java serialization.


On the same topic :

  • Java: load an object saved on hard disk after refactoring => “class not found” exception :/


来源:https://stackoverflow.com/questions/3884492/how-can-i-change-package-for-a-bunch-of-java-serializable-classes

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