ReflectionUtil { public static void mergeObject(Object from, Object to, boolean ignoreNullValue, Set<String> ignores) { try { Map<String, Object> settablePropertiesMap = Maps.newHashMap(); PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(from.getClass()); for (PropertyDescriptor property : propertyDescriptors) { if (property.getReadMethod() == null || property.getWriteMethod() == null) { continue; } Object value = property.getReadMethod().invoke(from); if ((value != null || !ignoreNullValue) && !ignores.contains(property.getName())) { settablePropertiesMap.put(property.getName(), value); } } for (Map.Entry<String, Object> settableProperty : settablePropertiesMap.entrySet()) { String propertyName = settableProperty.getKey(); Object propertyValue = settableProperty.getValue(); setPropertyValue(to, propertyName, propertyValue); } } catch (IllegalAccessException | InvocationTargetException | BeansException e) { throw new InvalidArgumentException("Cannot merge object", e); } } private  ReflectionUtil(); static Class<?> getGenericArgumentType(Class<? extends T> implementationClass, Class<T> genericClass, int index); static T getAnnotation(Class<?> clazz, final Class<T> annotationClass, final PropertyDescriptor property); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static void mergeObject(Object from, Object to, boolean ignoreNullValue, Set<String> ignores); static void mergeObject(Object from, Object to, String... ignores); static Object getPropertyValue(Object object, String property); static void setPropertyValue(Object object, String property, Object value); static Field getDeclaredField(Class<?> clazz, String fieldName); static Field getDeclaredField(Class<?> clazz, Class<? extends Annotation> annotationClass); static boolean isPrimitiveOrWrapperOrString(Class<?> clazz);  }
@Test public void mergeObjectTest() throws JsonProcessingException { MergedObject mergedObject = new MergedObject(); mergedObject.setId("an id"); mergedObject.setText("text"); mergedObject.setNumber(4); MergeRequest mergeRequest = new MergeRequest(); mergeRequest.setText("another text"); mergeRequest.setNumber("5"); ReflectionUtil.mergeObject(mergeRequest, mergedObject); Assert.assertEquals(5, mergedObject.getNumber().intValue()); Assert.assertEquals("another text", mergedObject.getText()); Assert.assertEquals("an id", mergedObject.getId()); }
@Test public void mergeObjectTestWithUnknownField() throws JsonProcessingException { MergedObject mergedObject = new MergedObject(); mergedObject.setId("an id"); mergedObject.setText("text"); mergedObject.setNumber(4); MergeRequest mergeRequest = new MergeRequest(); mergeRequest.setText("another text"); mergeRequest.setNumber("5"); mergeRequest.setBadField("bad"); ReflectionUtil.mergeObject(mergeRequest, mergedObject); }