public static void copyBeans(Object source, Object target) {
if (source == null || target == null) {
return;
}
Class sourceClass = source.getClass();
Class targetClass = target.getClass();
Field[] sourceClassFields =sourceClass.getDeclaredFields();
Field[] targetClassFields=targetClass.getDeclaredFields();
try {
for (Field field : sourceClassFields) {
if (!contiansName(targetClassFields,field.getName())) {
continue;
}
Field targetField = targetClass.getDeclaredField(field.getName());
if (targetField != null) {
if (field.getType().equals(targetField.getType())) {
field.setAccessible(true);
Object value = field.get(source);
field.setAccessible(false);
targetField.setAccessible(true);
targetField.set(target, value);
targetField.setAccessible(false);
}
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
protected static boolean contiansName(Field[] fields,String fieldName) {
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return true;
}
}
return false;
}
|