Difference between revisions of "Serialization"
From Suhrid.net Wiki
Jump to navigationJump to search (→Intro) |
(→Intro) |
||
Line 9: | Line 9: | ||
<syntaxhighlight lang="java5"> | <syntaxhighlight lang="java5"> | ||
− | |||
− | |||
class Thing { | 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; | ||
+ | } | ||
} | } | ||
Line 35: | Line 47: | ||
public static void main(String[] args) { | public static void main(String[] args) { | ||
− | Majig m1 = new Majig(1, new Thing()); | + | Majig m1 = new Majig(1, new Thing("T1")); |
− | Majig m2 = new Majig(2, new Thing()); | + | Majig m2 = new Majig(2, new Thing("T2")); |
File savFile = new File("majig.sav"); | File savFile = new File("majig.sav"); | ||
Line 55: | Line 67: | ||
} | } | ||
− | |||
</syntaxhighlight> | </syntaxhighlight> | ||
− | |||
[[Category:OCPJP]] | [[Category:OCPJP]] |
Revision as of 00:25, 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.
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();
}
}
}