Search code examples
javagenericsclone

How to properly implement the call to clone() in a generic class [Java]


I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method

genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
E data;

//code

public E get(){
return this.data.clone()
}
}

However this doesn't work in practice

package securedatacontainer;

public class Demo {


    public static void main(String[] args) throws CloneNotSupportedException {

        String s = "user";
        A a = new A(5, s);
        A b = a.clone();
        System.out.println("a equals b: " +(a.equals(b)));
        System.out.println("a == b: " + (a == b));


        B<A> c = new B<>(a);
        System.out.println("a equals c.data: " +(a.equals(c.data)));
        System.out.println("a == c.data: " + (a == c.data));

        A k = c.get();
        System.out.println(k.value);

    }

}


class A implements Cloneable{
    int value;
    String name;


    public A(int x, String str ){
        this.value = x;
        this.name  = str;
    }

    @Override
    public A clone() throws CloneNotSupportedException {
    A temp = new A(this.value, this.name);
    return temp;
    }


    public boolean equals(A elem){
        return (this.name).equals(elem.name) && this.value==elem.value;
    }
}




class B <E extends Cloneable>{
    E data;

    public B(E elem){
        this.data=elem;
    }

    public E get() throws CloneNotSupportedException{
        return (E) this.data.clone();
    }


}

I get

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
    at securedatacontainer.B.get(Demo.java:60)
    at securedatacontainer.Demo.main(Demo.java:19)

Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method


Solution

  • Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. 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.

    So here's my solution,

    public class B<E extends Cloneable> {
        E data;
    
        public B(E elem) {
            this.data = elem;
        }
    
        @SuppressWarnings("unchecked")
        public E get() {
            Method clone = null;
            try {
                clone = data.getClass().getMethod("clone");
                Object[] args = new Object[0];
                return (E) clone.invoke(data, args);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
    
        }
    }
    

    Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.

    @Override
    public A clone() throws CloneNotSupportedException {
        A temp = new A(this.value, this.name);
        return temp;
    } 
    

    If you want to make use of that facility you have to implement it like so,

    public class A implements Cloneable {
        int value;
        String name;
    
        public A(int x, String str) {
            this.value = x;
            this.name = str;
        }
    
        @Override
        public A clone() throws CloneNotSupportedException {
            return (A) super.clone();
        }
    
        public boolean equals(A elem) {
            return (this.name).equals(elem.name) && this.value == elem.value;
        }
    }
    

    In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.

    Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.

    B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.
    

    So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.