How to deal with a Java serialized object whose package changed?

后端 未结 4 934
礼貌的吻别
礼貌的吻别 2020-12-30 02:38

I have a Java class that is stored in an HttpSession object that\'s serialized and transfered between servers in a cluster environment. For the purpose of this explanation,

4条回答
  •  旧时难觅i
    2020-12-30 03:09

    I found this blog post that claims to have a solution, though it doesn't spell it out very clearly.

    What it is actually saying is that you create a subclass of ObjectInputStream that overrides the readClassDescriptor method to do something like this:

    @Override
    protected java.io.ObjectStreamClass readClassDescriptor() 
            throws IOException, ClassNotFoundException {
        ObjectStreamClass desc = super.readClassDescriptor();
        if (desc.getName().equals("oldpkg.Widget")) {
            return ObjectStreamClass.lookup(newpkg.Widget.class);
        }
        return desc;
    };
    

    You should also look at this SO question and its answers which cover some of the same ground as your question.

    My advice would be: don't support the case where old versions of software read data serialized by the new version.

    • This is a good opportunity to encourage (actually force) people to upgrade to the latest version of the code-base. Generally speaking, it is in everyone's interest that this happen sooner rather than later.

    • If it is premature to force people to upgrade for other reasons, then (IMO) you should seriously consider backing out your changes to the class / package names. Wait until you've got a clear strategy / plan for upgrading that is 1) technically sound, and 2) acceptable to all stakeholders.

提交回复
热议问题