JUtil { public static void copyProperties(Object target, Object source) throws IkasoaException { final Class<?> sourceClz = source.getClass(), targetClz = target.getClass(); Field[] fields = sourceClz.getDeclaredFields(); if (fields.length == 0) fields = sourceClz.getSuperclass().getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Field targetField = null; try { targetField = targetClz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { try { targetField = targetClz.getSuperclass().getDeclaredField(fieldName); } catch (NoSuchFieldException | SecurityException e1) { throw new IkasoaException(e1); } } if (ObjectUtil.same(field.getType(), targetField.getType())) { final String getMethodName = StringUtil.merge("get", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1)); final String setMethodName = StringUtil.merge("set", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1)); Method getMethod, setMethod; try { try { getMethod = sourceClz.getDeclaredMethod(getMethodName, new Class[] {}); } catch (NoSuchMethodException e) { getMethod = sourceClz.getSuperclass().getDeclaredMethod(getMethodName, new Class[] {}); } try { setMethod = targetClz.getDeclaredMethod(setMethodName, field.getType()); } catch (NoSuchMethodException e) { setMethod = targetClz.getSuperclass().getDeclaredMethod(setMethodName, field.getType()); } setMethod.invoke(target, getMethod.invoke(source, new Object[] {})); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IkasoaException(e); } catch (NoSuchMethodException e) { } catch (Exception e) { log.warn("Object copy failed : {}", e.getMessage()); } } else { throw new IkasoaException("Object copy failed ! Attribute type error !"); } } }  static void fur(int startIndex, int maxIndex, int spanNum, IntConsumer action); static void copyProperties(Object target, Object source);  }
@Test public void testCopyProperties() { ClassA classA = new ClassA(); ClassB classB = new ClassB(); classA.setStr1("string1"); classA.setStr2("string2"); classA.setInt1(123); try { JUtil.copyProperties(classB, classA); } catch (Exception e) { fail(); } assertEquals(classA.getStr1(), classB.getStr1()); assertEquals(classA.getStr2(), classB.getStr2()); assertEquals(classA.getInt1(), classB.getInt1()); }