Java Java.io.ObjectInputStream.defaultReadObject() 方法

  • 描述

    java.io.ObjectInputStream.defaultReadObject()方法用于从这个ObjectInputStream读取当前类的非静态和非瞬态字段,它间接地涉及到该类的readObject()方法的帮助。
  • 声明

    以下是java.io.ObjectInputStream.defaultReadObject()方法的声明。
     public void defaultReadObject()
  • 参数

    不适用
  • 返回值

    此方法不返回值。
  • 异常

    IOException如果发生I / O错误。
  • 例子

    以下示例显示java.io.ObjectInputStream.close()方法的用法。
     
    package com.jc2182; 
    import java.io.*; 
     
    public class DefaultReadObject {
     public static void main(String[] args) throws Exception {
      // Instantiates ObjectOutputStream , ObjectInputStream 
      // FileInputStream and FileOutputStream
      FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
      ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
      FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
      ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);
     
      // By using writeObject() method is to
      // write object to Serialized class
      obj_out_stm.writeObject(new DefaultObjectClass());
      obj_out_stm.flush();
     
      // By using readObject() method is to
      // read an object from the Serialized class
      DefaultObjectClass def_obj = (DefaultObjectClass) obj_in_stm.readObject();
     
      // Using both readObject and defaultReadObject(); 
      System.out.println("obj_in_stm.defaultReadObject(): " + def_obj.str);
      System.out.println("obj_in_stm.defaultReadObject(): " + def_obj.in);
     }
     
     static class DefaultObjectClass implements Serializable {
      String str = "Java Programming";
      Integer in = new Integer(10);
      private void readObject(ObjectInputStream obj_stm) throws IOException, ClassNotFoundException {
       // By using defaultReadObject() method is 
       // to read non-static fields of the present 
       // class from the ObjectInputStream
       obj_stm.defaultReadObject();
      }
     }
    }
    
    
    让我们编译并运行以上程序,这将产生以下结果-
     
    obj_in_stm.defaultReadObject(): Java Programming
    obj_in_stm.defaultReadObject(): 10