Serialization

From Suhrid.net Wiki
Revision as of 00:25, 30 August 2011 by Suhridk (talk | contribs) (→‎Intro)
Jump to navigationJump to search

Intro

  • Mechanism to persist state of objects
  • ObjectOutputStream.writeObject() - serialize and write
  • ObjectInputStream.readObject() - read and deserialize
  • Object and its complete object graph being seralized must implement the Serializable interface.
  • If any object needs to be skipped from the serialization process - mark it as transient.
  • In below example, Thing is not serializable, so when a Thing is used as a field in Majig the field is marked as transient.
class Thing {
	
	private String name;
	
	public Thing(String name) {
		this.name = name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
}

class Majig implements Serializable {
	private int id;
	
	private transient Thing t;
	
	public int getID() {
		return id;
	}
	
	Majig(int id, Thing t) {
		this.id = id;
		this.t = t;
	}
}

public class Ser1 {

	public static void main(String[] args) {
		
		Majig m1 = new Majig(1, new Thing("T1"));
		Majig m2 = new Majig(2, new Thing("T2"));
		
		File savFile = new File("majig.sav");
		
		try {
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(savFile));
			
			os.writeObject(m1);
			os.writeObject(m2);
			
			System.out.println("Serialized m1 and m2");
			
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}