如果序列化是在层次结构中继承的,那么将调用未实现serializable的类的构造函数.为什么会这样?

Jyo*_*rup 0 java serialization

为什么在反序列化时调用Food and Fruit类的构造函数,因为在下面的示例中没有调用SkinFruit和Banana2的构造函数?

假设我有以下类层次结构

class Food{
  public Food() { System.out.println("1"); } 
    }

class Fruit extends Food {
    public Fruit() { System.out.print("2"); }
}

class SkinFruit extends Fruit implements Serializable{
    SkinFruit() { System.out.print("3"); }
}
public class Banana2 extends SkinFruit { 
  private static final long serialVersionUID = 1L;
  int size = 42;

     public static void main(String [] args) {
       Banana2 b = new Banana2();
       FileOutputStream fost;
        try {
            fost = new FileOutputStream(new File("d:/testbanana.ser"));
            ObjectOutputStream oostr= new ObjectOutputStream(fost);
            oostr.writeObject(b);
            oostr.flush();          
            oostr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileInputStream fin= new FileInputStream(new File("d:/testbanana.ser"));
            ObjectInputStream objin= new ObjectInputStream(fin);
             b=(Banana2)objin.readObject();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


       System.out.println(" restored "+ b.size + "" );
     }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*rdt 5

因为这就是(de)序列化的工作原理.它是一种与常规对象构造不同的机制.

如果调用类A的构造函数,那是因为类A本身没有实现Serializable.在反序列化期间,将调用继承层次结构中第一个非可序列化类的无参数构造函数(可能是java.lang.Object).如果该类没有无参数构造函数,则会出现异常.