把一个对象赋值到另一个新对象,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();
}
}
}
作者:SpringWater
出处:https://www.cnblogs.com/springwater/
本博客所有文章仅用于学习、研究和交流目的,欢迎非商业性质转载。
博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高,不足和错误之处在所难免,希望大家能够批评指出。
博主是利用读书、参考、引用、抄袭、复制和粘贴等多种方式打造成自己的文章,请原谅博主成为一个无耻的文档搬运工!