Last active
February 1, 2023 06:51
-
-
Save scpurcell/9f8c80b6af0f6e3314fb to your computer and use it in GitHub Desktop.
Java - using reflection to copy matching fields from one object to another
This file contains hidden or 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
/** | |
* Use reflection to shallow copy simple type fields with matching names from one object to another | |
* @param fromObj the object to copy from | |
* @param toObj the object to copy to | |
*/ | |
public static void copyMatchingFields( Object fromObj, Object toObj ) { | |
if ( fromObj == null || toObj == null ) | |
throw new NullPointerException("Source and destination objects must be non-null"); | |
Class fromClass = fromObj.getClass(); | |
Class toClass = toObj.getClass(); | |
Field[] fields = fromClass.getDeclaredFields(); | |
for ( Field f : fields ) { | |
try { | |
Field t = toClass.getDeclaredField( f.getName() ); | |
if ( t.getType() == f.getType() ) { | |
// extend this if to copy more immutable types if interested | |
if ( t.getType() == String.class | |
|| t.getType() == int.class || t.getType() == Integer.class | |
|| t.getType() == char.class || t.getType() == Character.class) { | |
f.setAccessible(true); | |
t.setAccessible(true); | |
t.set( toObj, f.get(fromObj) ); | |
} else if ( t.getType() == Date.class ) { | |
// dates are not immutable, so clone non-null dates into the destination object | |
Date d = (Date)f.get(fromObj); | |
f.setAccessible(true); | |
t.setAccessible(true); | |
t.set( toObj, d != null ? d.clone() : null ); | |
} | |
} | |
} catch (NoSuchFieldException ex) { | |
// skip it | |
} catch (IllegalAccessException ex) { | |
log.error("Unable to copy field: {}", f.getName()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
immutable types : We can add BigDecimal as well 👍