首页 > 其他 > 详细

把一个对象赋值到另一个新对象,copy工具类

时间:2021-05-08 16:13:18      阅读:24      评论:0      收藏:0      [点我收藏+]
前提条件:两个类字段名字一致,只是名字不一样!
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();
}
}
}

把一个对象赋值到另一个新对象,copy工具类

原文:https://www.cnblogs.com/springwater/p/14744969.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!