简体   繁体   中英

Extract java superclass from serializable object with backwards compatibility

I would like to move class functionality to a parent class, but this will brake down the de-serialization. The starting point is this:

package xso.test.serializable;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class WriteClass
{
  public static void main( String[] args ) throws Exception
  {
    MyClass d = new MyClass();
    d.i = 888;

    try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "MyClass.ser" ) ))
    {
      System.out.println( "Serializing" );
      oos.writeObject( d );
    }
  }
}

class MyClass implements Serializable
{
  /**
   * same serialVersionID as in ReadClassNew
   */
  private static final long serialVersionUID = -4436695035358861227L;

  int i = 10;
}

I would like to extract MyClass to a new SuperClass (MyNewParentClass) like this:

package xso.test.serializable;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class ReadClassNew
{
  public static void main( String[] args ) throws Exception
  {
    ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "MyClass.ser" ) );
    System.out.println( "Deserializing" );
    MyClass clazz = (MyClass)ois.readObject();
    System.out.println( clazz.i );
  }
}

class MyNewParentClass implements Serializable
{
  /**
   * 
   */
  private static final long serialVersionUID = -6437613570659781444L;

  int i = 10;
}

class MyClass extends MyNewParentClass
{
  /**
   * same serialVersionID as in WriteClass
   */
  private static final long serialVersionUID = -4436695035358861227L;

  //int i = 10; // moved to parent class. (Field will not serialized any more sadly )
}

To see and reproduce the problem:

  1. Run the first code snippet.
  2. Run the second code snippet. The console output will be:

      Deserializing 0 

if you uncomment the int i = 10; in the child class (MyClass) you can see the de-serialization can work. But I would like to de-serialization the field int i in the superclass.

Is this possible? Thanks for any suggestion.

I'd like to add something to EJP 's comment.

When an object is serialized, its entire object graph is serialized. That means any objects referenced by the serialized object's instance variables are serialized, and any object referenced by those objects...and so on. In your case class MyClass from the first snipped of code has no clue about class MyNewParentClass and it's variables, so basically those two point to the different bytes of memory on the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM