serialization - When does it make sense for a Java object to be Serializable but not Cloneable? -


If a Java class applies the serialjob interface but does not have a public clone in it () Method, it is usually possible to create a deep copy like this:

  class clonehalper {@SuppressWarnings ("uncheck") public static & lt; T extended serialized & gt; T clone (t oboj) {try {bytereutputstream baoos = new byteOnoutstream (); ObjectOutputStream OOS = New ObjectOutputStream (Baoos); Oos.writeObject (obj); Oos.close (); Byte [] Bytes = Baos Byteere (); Bytereinputstream bank = new bytereinputstream (bytes); ObjectInputStream OIS = new object intestust (bass); T copy = (t) ois.readObject (); Ois.close (); Return copy; } Hold (pre-Klassnotfound exception pre) {// should throw new error (ex); } Hold (IOException ex) {// Probably a bug in T's custom serialization methods throw new runtime exposition (ex); }}}  

I often face third-party library classes in this way and take up the hacks as above. I have ever expanded the object output speed so that this is not the cause of serious problems, disable (slow / temporarily encoding / decoding and floating serialization graph consume much memory Besides)

And if this technique is not safe to use, the serializable should not have been declared.

What I would like to know, if your class is serializable , then define which define you can be public clone () method ( Using either the Cloneable interface or the copy constructor?)


related:

OK, you are saying that the sorting mechanism is indirectly" clone "objects in a way. This is definitely not the primary task, it usually used to broadcast programs on the network to broadcast, or to store and read them later. You can expect to use an object in such a way, and implement serial jub, while not expecting to clone the code objects locally, and not clonable.

The fact is that the code is working through the serialization on the code object in no way using the author's intention, which can be a "mistake" of the author or the caller, But that does not mean that in general, it is usually customizable and cloned to go together.

Separately, I do not believe that the clone () is as difficult as "broken" to apply as hard as possible. The copy maker is more natural for using and receiving IPHOs.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -