Java Reference
In-Depth Information
System.out.println(newDog == Dog.INSTANCE);
System.out.println(newDog);
}
// This method is very slow and generally a bad idea!
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();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
To fix the problem, add a readResolve method to Dog , which turns the hidden constructor into a
hidden static factory that returns the one true Dog [EJ Items 2, 57]. With the addition of this method
to Dog , CopyDog will print true instead of false , indicating that the "copy" is in fact the original:
private Object readResolve() {
// Accept no substitutes!
return INSTANCE;
}
 
 
Search WWH ::




Custom Search