VO、PO、DTO、BO之间往往需要互转,
转换时,相同的字段值直接复制到新的对象上。
package com.helloworld.pojo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class PojoHelper {
/**
* 将一个对象的值拷贝至另一个对象
*
* @param source
* 数据来源的对象
* @param clazz
* 要转换的类型
* @return
*/
public static <T> T copy(Object source, Class<T> clazz) {
T result = null;
try {
result = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
if(source == null) {
return null;
}
Field[] sourceFields = source.getClass().getDeclaredFields();
for (Field field : fields) {
for (Field sourceField : sourceFields) {
if (field.getName().equals(sourceField.getName())) {
field.setAccessible(true);
if(Modifier.isStatic(field.getModifiers())) {
continue;
}
String name = field.getName();
String firstLetter = name.substring(0, 1).toUpperCase(); // 将属性的首字母转换为大写
String getMethodName = "get" + firstLetter + name.substring(1);
String setMethodName = "set" + firstLetter + name.substring(1);
// 获取方法对象
Method getMethod = source.getClass().getMethod(getMethodName, new Class[] {});
Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });// 注意set方法需要传入参数类型
// 调用get方法获取旧的对象的值
Object value = getMethod.invoke(source, new Object[] {});
// 调用set方法将这个值复制到新的对象中去
setMethod.invoke(result, new Object[] { value });
}
}
}
} catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
return result;
}
}