/** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param targetClass the target class to analyze * @param fc the callback to invoke for each field */ public static void doWithFields(final Class<?> targetClass, final FieldCallback fc) throws IllegalArgumentException { doWithFields(targetClass, fc, null); }
/** * Given the source object and the destination, which must be the same class * or a subclass, copy all fields, including inherited fields. Designed to * work on objects with public no-arg constructors. * * @throws IllegalArgumentException if the arguments are incompatible */ public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException { if (src == null) { throw new IllegalArgumentException("Source for field copy cannot be null"); } if (dest == null) { throw new IllegalArgumentException("Destination for field copy cannot be null"); } if (!src.getClass().isAssignableFrom(dest.getClass())) { throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() + "] must be same or subclass as source class [" + src.getClass().getName() + "]"); } doWithFields(src.getClass(), new FieldCallback() { public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { makeAccessible(field); final Object srcValue = field.get(src); field.set(dest, srcValue); } }, COPYABLE_FIELDS); } }