Once upon a time there was a person who thought there was only an unusual dog in the world, so he wrote the following class and wrote it
As a singleton [gamma95]:
Public class dog extends exception {public static final dog instance = new dog (); Private dog () {} Public String tostring () {return "woof ";}}
It turns out that this person's approach is wrong. You can create
2 dog instances?
This class may look like a single piece, but it is not. The problem is that dog extends exception,
Exception implements java. Io. serializable. This means that the dog is serializable.
And deserialization creates a hidden constructor.
As demonstrated in the following section, if you serialize dog. instance
The byte sequence is used to decode the sequence, and you will get another dog. This process
The value of false indicates that the new dog instance is different from the original one, and
After Woof is printed, it indicates that the new dog instance also has the following functions:
Import Java. io. *; public class copydog {// not to be confused with copycatpublic static void main (string [] ARGs) {dog newdog = (DOG) deepcopy (dog. instance); 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 correct this problem, you can add a readresolve Method to the dog to hide
The constructor is transformed into a hidden static factory to return the original dog
[J Items 2, 57]. After this method is added to the dog, copydog prints true instead
False indicates that the "DUPLICATE" is actually the original instance:
Private object readresolve () {// accept no substitues! Return instance ;}
The main lesson of this puzzle is that a single-piece class that implements serializable must have one
The readresolve method is used to return its unique instance. A secondary lesson is that
To extend a class that implements serializable, or because
The serializable interface makes serializable accidentally implemented. To platform designers
The lesson is that the hidden constructor, such as the one generated in serialization, will allow the reader to produce the program behavior.
Illusion.
Puzzle 83: Reading the gods of the needy