对象转化 复制相同属性

/**
* 对象转化(自动构造新对象,并复制相同属性的数据)
*
* @param o
* @param targetC
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(Object o, Class<T> targetC) {
Object targetO = null;
if (o == null) {
return (T) targetO;
}
try {
// 1.构造新对象
targetO = targetC.newInstance();
Field[] targetFields = targetC.getDeclaredFields();
// 2.向新对象写数据(循环读取老对象中数据写入新对象)
for (Field f : o.getClass().getDeclaredFields()) { // 循环处理类属性
if (!Modifier.isStatic(f.getModifiers())) {// 非静态变量才做处理
try {
// 2.1.读数据
Method rm = getMethod(f.getName(), o.getClass());// 获得读方法
Object val = rm.invoke(o);// 调用读方法
// 2.2.写数据
for (Field targetF : targetFields) {
if (f.getName().equals(targetF.getName())) {// 属性名相同
try {
Method wm = setMethod(targetF.getName(), targetC);// 获得写方法
wm.invoke(targetO, val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return (T) targetO;
}
原文地址:https://www.cnblogs.com/pxzbky/p/14837620.html