Created
May 23, 2018 01:36
-
-
Save bsharathchand/6c833b40d67ced9562791d567e2eb4a4 to your computer and use it in GitHub Desktop.
Object Cloning using Java Reflections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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