Interview Questions

How to use Cloneable type as parameter to Java generic class ?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

How to use Cloneable type as parameter to Java generic class ?

Because the method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. Personally I didn't think this would be a problem at first (hey, I'm a subclass of Object, so I should be able to call its protected methods, right?), but the compiler needs to know that you're a subclass of the target object's class (or in its package) in order to call protected methods, neither of which apply here.

The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.

The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers. An alternative would be to write your own MyCloneable interface which has a public clone() method declared on it; this might work if you'll only ever be passing your own domain classes in, but means that you couldn't use it on external classes (such as java.util.String or java.util.ArrayList) since you can't force them to implement your interface.

public class GenericTest<T extends Cloneable>
{
T obj;
GenericTest(T t)
{
obj = t;
}
T getClone()
{
// "The method clone() from the type Object is not visible."
return (T) obj.clone();
}
}

static Method clone = Object.class.getMethod("clone");
static public <T extends Cloneable>
T clone(T obj)
return (T) clone.invoke(obj);

(Continued on next question...)

Other Interview Questions