欢迎来到SpringWater的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

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

前提条件:两个类字段名字一致,只是名字不一样!
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();
}
}
}
posted @ 2021-05-08 15:01  骑ZHU看夕阳```  阅读(638)  评论(0编辑  收藏  举报