I was reading up on performing a deep-copy of an array correctly, however I was confused about how the #clone()
is implemented. It is a member of the java.lan
clone()
method is unnecessary, every object could invoke Object.clone
method by reflect, so an object can be cloned depends on whether to implement Cloneable
interface. This is for a security reason. You can simply clone an object which implements Cloneable
by this util:
@SuppressWarnings("unchecked")
public static T clone(Cloneable obj) {
T rtn = null;
try {
Method method = Object.class.getDeclaredMethod("clone");
method.setAccessible(true);
rtn = (T) method.invoke(obj);
} catch (Throwable t) {
t.printStackTrace();
}
return rtn;
}