使用反射原理逐层获取对应的字段值,再读取到新对象中
package com.myjava.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @ClassName: Pojo2PojoUtil.java
* @Description: 一个实体类转为另外一个结构相同但具体字段有差异的实体
*
* @version: v1.0.0
* @author: 87655
* @date: 2021年7月7日 上午9:50:50
*/
public class Pojo2PojoUtil {
public static <T> Object Pojo2Pojo(Class<T> classDest, Object object) throws Exception {
Field fields[] = classDest.getDeclaredFields();
T t = classDest.newInstance();
Class<? extends Object> classOrgin = object.getClass();
String fieldname = "";
String setMethodname = "";
String getMethodname = "";
Object methodsetvalue = "";
// 遍历所有字段,对应配置好的字段并赋值
for (Field field : fields) {
if (null != field) {
// 获取字段名称
fieldname = field.getName();
// 拼接set方法
setMethodname = "set" + StrUtil.capitalize(fieldname);
getMethodname = "get" + StrUtil.capitalize(fieldname);
//
try {
if (!"serialVersionUID".equals(fieldname)) {
//如果包含了包名,那么可以认为是一个子类或者
if (field.getType().toString().contains("com.myjava.pojo.")) {
Method getMethod = classOrgin.getDeclaredMethod(getMethodname);
Object subObject = getMethod.invoke(object);
methodsetvalue = Pojo2Pojo(field.getType(), subObject);
} else {
try {
Method getMethod = classOrgin.getDeclaredMethod(getMethodname);
methodsetvalue = getMethod.invoke(object);
}catch(NoSuchMethodException e) {
//传入对象没有该字段或者方法
System.err.println("传入对象没有该字段或者方法:"+getMethodname);
}
}
// 赋值给字段
Method setMethod = classDest.getDeclaredMethod(setMethodname, field.getType());
setMethod.invoke(t, methodsetvalue);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
return t;
}
}