ObjectInputStream.readFields() has the following syntax.
public ObjectInputStream.GetField readFields() throws IOException , ClassNotFoundException
In the following code shows how to use ObjectInputStream.readFields() method.
/*from ww w . j a v a2 s. c o m*/ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; public class Main implements Serializable { public static void main(String[] args) throws Exception { FileOutputStream out = new FileOutputStream("test.txt"); ObjectOutputStream oout = new ObjectOutputStream(out); oout.writeObject(new Example()); oout.flush(); oout.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream( "test.txt")); Example a = (Example) ois.readObject(); System.out.println(a.isDefault); System.out.println(a.string); ois.close(); } } class Example implements Serializable { String string = "Hello World!"; boolean isDefault; private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField( "string", String.class) }; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); isDefault = fields.defaulted("string"); string = (String) fields.get("string", null); } private void writeObject(ObjectOutputStream out) throws IOException { ObjectOutputStream.PutField fields = out.putFields(); fields.put("string", string); out.writeFields(); } }
The code above generates the following result.