Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen does it make sense for a Java object to be Serializable but not Cloneable?
    primarykey
    data
    text
    <p>If a Java class implements the <code>Serializable</code> interface but does not have a public <code>clone()</code> method, it is usually possible to create a deep copy like this:</p> <pre><code>class CloneHelper { @SuppressWarnings("unchecked") public static &lt;T extends Serializable&gt; T clone(T obj) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); T copy = (T) ois.readObject(); ois.close(); return copy; } catch (ClassNotFoundException ex) { // Shouldn't happen throw new Error(ex); } catch (IOException ex) { // Probably a bug in T's custom serialization methods throw new RuntimeException(ex); } } } </code></pre> <p>I often encounter third-party library classes like this and resort to hacks like the one above. I've even extended <code>ObjectOutputStream</code> on occasion to make the copy shallower. It's never caused serious problems, other than being inefficient (slow to encode/decode and the temporary serialization graphs can consume a lot of memory.)</p> <p>And if it is not safe to use this technique, the class probably should not have been declared <code>Serializable</code>.</p> <p>So what I would like to know is, if your class is <code>Serializable</code>, what might prevent you from defining a public <code>clone()</code> method (using either the <code>Cloneable</code> interface or a copy constructor?)</p> <hr> <p>Related: <a href="https://stackoverflow.com/questions/475842/copy-an-object-in-java">Copy an object in Java</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload