C
castillo.bryan
I just came across a class that uses serialization to clone itself.
Its a class that is a base class for about 30 different classes that
represent items stored in a relational database. I understand that the
programmer did this so they could clone any object inherting from the
base class, without writing anything else. I'm not sure if this is
really a good idea or not though. Any opinions?
public Object clone() {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(this);
bais = new ByteArrayInputStream(baos.toByteArray());
ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
finally {
if (oos != null) try { oos.close(); } catch (IOException ioe) {}
if (ois != null) try { ois.close(); } catch (IOException ioe) {}
}
}
Its a class that is a base class for about 30 different classes that
represent items stored in a relational database. I understand that the
programmer did this so they could clone any object inherting from the
base class, without writing anything else. I'm not sure if this is
really a good idea or not though. Any opinions?
public Object clone() {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(this);
bais = new ByteArrayInputStream(baos.toByteArray());
ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
finally {
if (oos != null) try { oos.close(); } catch (IOException ioe) {}
if (ois != null) try { ois.close(); } catch (IOException ioe) {}
}
}