Difference between revisions of "Serialization"

From Suhrid.net Wiki
Jump to navigationJump to search
(Created page with "== Intro == * Mechanism to persist state of objects * ObjectOutputStream.writeObject() - serialize and write * ObjectInputStream.readObject() - read and deserialize [[Catego...")
 
Line 4: Line 4:
 
* ObjectOutputStream.writeObject() - serialize and write
 
* ObjectOutputStream.writeObject() - serialize and write
 
* ObjectInputStream.readObject() - read and deserialize
 
* 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.
 +
 +
<syntaxhighlight lang="java5">
 +
 +
import java.io.*;
 +
 +
class Thing {
 +
 +
}
 +
 +
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());
 +
Majig m2 = new Majig(2, new Thing());
 +
 +
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();
 +
}
 +
}
 +
 +
}
 +
 +
 +
</syntaxhighlight>
  
  
  
 
[[Category:OCPJP]]
 
[[Category:OCPJP]]

Revision as of 00:23, 30 August 2011

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.
import java.io.*;

class Thing {
	
}

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());
		Majig m2 = new Majig(2, new Thing());
		
		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();
		}
	}

}