Serialization中的readObjectNoData

readObjectNoData方法是JDK1.4中增加的. 但一直以来, 国内外的书上都只是提到而已, 没有真正涉及到例子.

今天有学生问到其用法, 说明一下.

readObjectNoData 
  原始情况
    pojo
		public class Person implements Serializable {               
			private int age;                
			public Person() {  }              
			//setter getter...      
		}
    序列化
         Person p = new Person();             
		 p.setAge(10);             
		 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/person.ser"));             
		 oos.writeObject(p);            
		 oos.flush();             
		 oos.close();
  类结构变化后, 序列化数据不变     pojo
      Animal
        implements Serializable
        显式编写readObjectNoData
        public class Animal implements Serializable {                  
				private String name;                 
				public Animal() {  }                 
				//setter getter...                 
				private void readObjectNoData() {                       
					this.name = "zhangsan";                 
				}          
		}
      Person 
        extends Animal
        public class Person extends Animal implements Serializable {                  
				private int age;                  
				public Person() {  }                 
				// setter getter...         
		}
    反序列化
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:/person.ser"));       
	  Person sp = (Person) ois.readObject();       
	  System.out.println(sp.getName());
      readObject时, 会调用readObjectNoData


 

 

 

 

 

 


 

你可能感兴趣的:(jdk,c,String,serialization,Class,setter)