Java Reference
In-Depth Information
< Day Day Up >
Puzzle 91: Serial Killer
This program creates an object and checks that it obeys a class invariant. Then the program
serializes the object, deserializes it, and checks that the deserialized copy also obeys the invariant.
Does it? If not, why not?
import java.util.*;
import java.io.*;
public class SerialKiller {
public static void main(String[] args) {
Sub sub = new Sub(666);
sub.checkInvariant();
Sub copy = (Sub) deepCopy(sub);
copy.checkInvariant();
}
// Copies its argument via serialization (See Puzzle 83)
static public Object deepCopy(Object obj) {
try {
ByteArrayOutputStream bos =
new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
return new ObjectInputStream(bin).readObject();
 
 
Search WWH ::




Custom Search