简体   繁体   English

自定义继承类的序列化

[英]custom serialization of inherited class

If want to write custom serialization method for derived class , Do I have to read and write base class fields again? 如果要为派生类编写自定义序列化方法,是否需要再次读写基类字段?

A implements Serializable
{
   field1,
   field2 etc

      private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException
    {
      // read in field1
      //read in field2
    }

     private void writeObject(ObjectOutputStream outputStream) throws IOException
    {
       // write field1 to output stream
      //write field 2 to output stream
      }
}

Class B extends A
{
  field 3

      private void writeObject(ObjectOutputStream outputStream) throws IOException
    {
       //TODO : should contain only field 3 or field1,field2 and field 3?
    }

}

If you are calling writeObject on object of type B, it will not implicitly call the writeObject method in class A. You will have to call it yourself using super.writeObject(outStream) or else you can set all the three fields in the child method itself. 如果要在类型B的对象上调用writeObject ,则不会隐式调用类A中的writeObject方法。您必须自己使用super.writeObject(outStream)进行调用,否则可以在child方法中设置所有三个字段本身。 In short, the writeObject function in B should contain all three fields in your case. 简而言之,在您的情况下,B中的writeObject函数应包含所有三个字段。

If you're overriding the method, you need to re-implement everything the parent class did as well. 如果要覆盖该方法,则需要重新实现父类所做的所有操作。

As soon as you create a method in the derived class with the same signature as the parent class, it is overridden and the parent's method is no longer used for objects of type B. 一旦在派生类中创建与父类具有相同签名的方法,该方法就会被覆盖,并且父类的方法不再用于B型对象。

Depending on your use case, you may want to consider using an abstract class. 根据您的用例,您可能需要考虑使用abstract类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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