4 Replies Latest reply: Dec 22, 2009 2:23 PM by 843790 RSS

    Serialization after package path changed

    843790
      So, I had working code, but then decided to reorganize my class structure a bit. My object "TriggerProject" was moved from package 'triggerhelper' to 'triggerhelper.dataHolders'. The class itself is serializable and I was able to write it to a file and open it up with no problems - before I changed package names. As of now however, I get a ClassCastException because the serialized file assumed the Object was from the original package. This is not impeding me on moving forward, because I know the newly created files will save and open correctly - but it just got me curious wondering if there was a way to fix it. Like, if there was some way to cast the old package path to my new one.

      Forgive my ill-knowledge of the subject if the answer is completely obvious.

      -the code that breaks-
      //aFile is of type File...
      TriggerProject openedProject = null;
      FileInputStream fis = null;
      ObjectInputStream in = null;
      try{
        fis = new FileInputStream(aFile);
        in = new ObjectInputStream(fis);
        openedProject = (TriggerProject) in.readObject(); // <-- ClassCastException
        in.close();
      }//catch etc...
        • 1. Re: Serialization after package path changed
          EJP
          You have to deploy a set of classes in the original package, with serialVersionUIDs equal to the old ones, and with readResolve() methods that map the old classes to the new ones.
          • 2. Re: Serialization after package path changed
            843790
            So basically there is no clean way to do it? I understand that the problem shouldn't occur in the first place (good planning lends itself to not reorganizing code). From what you're saying though, it seems as if re-routing object reads are done with hardcoded empty classes - as opposed to ideally taking care of it in the local spot in which it's called.

            If there is no way to take care of it at the spot of the object read (the line where the classCastException occurs), then my question has been answered, but if there is I would like to know it.
            • 3. Re: Serialization after package path changed
              EJP
              So there is no clean way to do it?
              That is the 'clean way to do it.
              ideally taking care of it in the local spot in which it's called
              Impossible, because the object can't be deserialized unless the class that serialized it is present. Your notion of 'ideal' notwithstanding.
              • 4. Re: Serialization after package path changed
                843790
                I didn't understand why it was impossible until that last reply - for some reason it sank in.

                Thanks for your time and help,
                Phil