A method to clone any clonable object.
- By Steve Ball
- September 12, 2000
EFFECTIVE JAVAEnhancing container classes with deep-copy semantics
Steve Ball
Listing 1. A method to clone any clonable object.
public class GeneLab {
public static Object clone(Object obj) {
if (obj == null) return null;
try {
// use the Clonable interface if the object implements it
return ((Clonable) obj).clone();
} catch (ClassCastException e) {}
// handle wrapper types and other immutable classes
if (obj instanceof Boolean) return obj;
if (obj instanceof Character) return obj;
if (obj instanceof Number) return obj;
if (obj instanceof String) return obj;
Class objClass = obj.getClass();
try {
// try accessing public clone method using reflection
return objClass.getMethod("clone", null).invoke(obj, null);
} catch (Exception e) {}
try {
// try accessing copy constructor using reflection
Class[] params = new Class[] { objClass };
Object[] args = new Object[] { obj };
return objClass.getConstructor(params).newInstance(args);
} catch (Exception e) {}
// handle known classes as special cases
if (obj instanceof java.util.Date)
return new java.util.Date(((java.util.Date) obj).getTime());
throw new CannotCloneObjectException(); // give up
}
private GeneLab() {}
}