Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #35473
| Newsgroups | comp.lang.java.programmer |
|---|---|
| Date | 2016-08-26 11:56 -0700 |
| Message-ID | <3bfbd6f7-8b66-4733-9d52-68f498ee84ba@googlegroups.com> (permalink) |
| Subject | What's the best way to clone a generic object? |
| From | Eric Douglas <e.d.programmer@gmail.com> |
For example:
public class MainClass<T extends MyGeneric> {
private T copyFrom;
private T copyTo;
public void copyIt() {
// code here to turn copyTo into a deep copy of copyFrom
}
}
public abstract class MyGeneric {
}
public class OneExample extends MyGeneric {
private String s;
private int i;
}
public class AnotherExample extends MyGeneric {
private String s;
private byte[] b;
}
I searched the web and they generally said don't use Cloneable.
Here are some of the answers.
1) Require a method in every extended class that would create a new instance of itself and manually copy every member. Since my base class is abstract this could be an abstract method, otherwise could require an interface (does that even force subclasses to implement?).
2) Add the deepClone dependency. https://github.com/kostaskougios/cloning
3) Serialize. which simply means copyTo = serialize(copyFrom) as follows
public static <T> T serialize(final T testObject) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
T endTestObject;
try {
final ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(testObject);
oos.close();
// deserialize
final byte[] streamingBytes = out.toByteArray();
final ByteArrayInputStream in = new ByteArrayInputStream(streamingBytes);
final ObjectInputStream ois = new ObjectInputStream(in);
endTestObject = (T) ois.readObject();
endTestObject.getClass();
} catch (final Exception e) {
return null;
}
return endTestObject;
}
Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread
What's the best way to clone a generic object? Eric Douglas <e.d.programmer@gmail.com> - 2016-08-26 11:56 -0700 Re: What's the best way to clone a generic object? Marcel Mueller <news.5.maazl@spamgourmet.org> - 2016-08-27 07:47 +0200
csiph-web