custom clone method java code example

Example: java generic calling clone method

/* 	If you have a generic class where you want to call your generic object's
	clone method, add this clone method to your class. */

public class customClass<E extends Cloneable> {
	private LinkedList<E> lst;
  
    public customClass() {
		// Constructor stuff
    }

	// Creates a new list with elements starting at index n through end of lst.
    public LinkedList<E> partialList(int n) {
		LinkedList<E> parLst = new LinkedList<>();
        for (int i = n; i < lst.size() - 1; i++) {
            parLst.add(clone(mlist.get(i))); // Adds deep copied objects to new list.
        }
        return parLst;
    }
	
	// The deep copy method for generic object.
    private E clone(E element) {
        Class c = element.getClass();
        
        try {
            Method m = c.getMethod("clone", (Class) null);
            return (E) m.invoke(element, (E) null);
        }
        catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            return null;
        }
    }
}

Tags:

Java Example