Cloneable type parameter?
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
}
}
After RTFM on how generics actually work, the error message is explainable:
T is unbounded, so the compiler sees me calling a protected method outside
of its class.
So here is my next attempt:
public class RestorableObject<T extends Cloneable> {
private T original;
private T workingCopy;
public RestorableObject(T obj) {
original = obj;
workingCopy = obj.clone(); // clone() not found in Cloneable
}
}
I should have seen this coming, since Cloneable is an empty interface,
and the docs state that
* By _convention_, classes that implement this interface should override
* Object.clone (which is protected) with a public method.
I guess nobody told javac about this _convention_ ... must be human thing.
I would like to make the compiler ensure that RestorableObject is
only wrapped around objects providing a clone() method. I can do
this by introducing an interface
public interface ReallyCloneable<T> {
public T clone();
}
and finally arriving at
public class RestorableObject<T extends ReallyCloneable<T>> {
private T original;
private T current;
public RestorableObject(T obj) {
original = obj;
current = obj.clone();
}
}
Is there a more elegant way of doing this?
Regards,
Stefan