custom clone method java code example
Example: java generic calling clone method
public class customClass<E extends Cloneable> {
private LinkedList<E> lst;
public customClass() {
}
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)));
}
return parLst;
}
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;
}
}
}