Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bsharathchand/6c833b40d67ced9562791d567e2eb4a4 to your computer and use it in GitHub Desktop.
Save bsharathchand/6c833b40d67ced9562791d567e2eb4a4 to your computer and use it in GitHub Desktop.
Object Cloning using Java Reflections
public Object cloneUsingReflections(Object value) {
// If Value is null then return
if (value == null)
return value;
// Use reflections to call the clone method on the object
try {
if (value instanceof Cloneable) {
Method cloneMethod;
cloneMethod = value.getClass().getMethod("clone");
Object clone = cloneMethod.invoke(value);
log.debug("Value : {} Clone : {}",value,clone);
return clone;
}
} catch (NoSuchMethodException e) {
log.debug("Cloning method not found for class : {}" , value.getClass().getName());
} catch (SecurityException e) {
log.debug("SecurityException while cloning object of class : {}" , value.getClass().getName());
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while cloning object of class : {}" , value.getClass().getName());
} catch (IllegalArgumentException e) {
log.debug("IllegalArgumentException while cloning object of class : {}" , value.getClass().getName());
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while cloning object of class : {}" , value.getClass().getName());
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment