Re: Cloneable type parameter?
Stefan Schmiedl wrote:
Greetings.
I'd like to define a wrapper class, whose instances keep read-only
copies of the original object passed in. I tried using generics for this:
public class RestorableObject<T> {
private T original;
private T workingCopy;
public RestorableObject(T obj) {
original = obj;
workingCopy = obj.clone(); // clone() is protected in Object
}
}
You need to use reflection to verify if T has an accessible clone()
method and invoke the method if you can get hold of one. The
serialization trick will not help much. You have to check if the object
is serializable. Anyhow using serialization is likely a great waste of
CPU cycles.
In both cases you are faced with another problem: What if T does not
provide clone() (or serialization)? Error message? Gamble and use the
original reference? Throw an exception? You decide.
In short, generics and cloning don't work well together. Yet another
reason why IMHO generics are am ugly, not well thought-out hack. clone()
was always a strange hack, and with generics two hacks collide.
/Thomas