Skip to content

Instantly share code, notes, and snippets.

@scpurcell
Last active February 1, 2023 06:51
Show Gist options
  • Save scpurcell/9f8c80b6af0f6e3314fb to your computer and use it in GitHub Desktop.
Save scpurcell/9f8c80b6af0f6e3314fb to your computer and use it in GitHub Desktop.
Java - using reflection to copy matching fields from one object to another
/**
* 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());
}
}
}
@gomahan
Copy link

gomahan commented Jan 7, 2021

immutable types : We can add BigDecimal as well 👍

@elgsylvain85
Copy link

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment