问题
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