前提条件:两个类字段名字一致,只是名字不一样!
public static void copySimpleObject(Object target, Object source) {
Map map;
Iterator iter;
if ((target != null) && (source != null)) {
List targetMethodList = ObjectUtils.getSetter(target.getClass());
List sourceMethodList = ObjectUtils.getGetter(source.getClass());
map = new HashMap();
for (Iterator iter2 = sourceMethodList.iterator(); iter2.hasNext();) {
Method method = (Method) iter2.next();
map.put(method.getName(), method);
}
for (iter = targetMethodList.iterator(); iter.hasNext();) {
Method method = (Method) iter.next();
String fieldName = method.getName().substring(3);
try {
Method sourceMethod = (Method) map.get("get" + fieldName);
if (sourceMethod == null) {
sourceMethod = (Method) map.get("is" + fieldName);
}
if (sourceMethod == null) {
continue;
}
Object value = sourceMethod.invoke(source, new Object[0]);
if (value != null) {
method.invoke(target, new Object[] { value });
}
} catch (Exception e) {
System.out.println("fieldName:"+fieldName);
e.printStackTrace();
}
}
}
原文:https://www.cnblogs.com/springwater/p/14744969.html