一、利用反射进行转换
/**
* 转换具体细节
*
* @param object 源
* @param target 目标
* @param <T> 泛型
* @return 返回传入对象类型
*/
private static <T> T swap(Object object, T target) {
//利用反射获取对象的所有属性(包括私有变量)
Field[] sourceFields = object.getClass().getDeclaredFields();
Field[] targetFields = target.getClass().getDeclaredFields();
for (Field targetField : targetFields) {
String targetName = targetField.getName();
for (Field sourceField : sourceFields) {
//对比两个类的相同名称的变量(只比较名称,不包含类型)
if (sourceField.getName().equals(targetName)) {
//获取传入object对象的targetName属性的值
Object value = getValue(object, targetName);
//赋予传入target对象的targetName属性的value值(类型若不匹配,IllegalArgumentException)
setValue(target, targetName, value);
}
}
}
return target;
}
private static Object getValue(Object sourceObject, String targetName) {
try {
Class clazz = sourceObject.getClass();
Field[] fields = sourceObject.getClass().getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
if (!name.equals(targetName)) {
continue;
}
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null) return readMethod.invoke(sourceObject);
}
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private static void setValue(Object targetObject, String targetName, Object value) {
try {
Class clazz = targetObject.getClass();
Field[] fields = targetObject.getClass().getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
if (!name.equals(targetName)) {
continue;
}
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
Method writeMethod = propertyDescriptor.getWriteMethod();
if (writeMethod != null) writeMethod.invoke(targetObject, value);
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
二、org.springframework.beans.BeanUtils中的方法
BeanUtils.copyProperties(source, target);