packagecom.wayne.common.utils;
importcom.google.common.collect.Lists;importcom.wayne.common.exception.CopyPropertyException;
importjava.lang.reflect.Field;importjava.lang.reflect.Method;importjava.util.List;
/***@authorWayne
* @date 2019/6/5*/
public classBaseUtil {
/*** 将一个集合中对象的值拷贝到另外一个对象,属性相同即赋值
*@paramsource 源数据,将此对象数据取出
*@paramtClass 目标对象,将取出的数据赋值到该对象中
*@param 源数据类型
*@param 目标数据类型
*@return被赋值后的目标对象集合
*@throwsCopyPropertyException 自定义异常,经过反射建立对象或调用方法时抛出的异常*/
public static List copyProperties(List source, Class tClass) throwsCopyPropertyException {
//判断传入源数据是否为空,若是空,则抛自定义异常
if(null ==source) {throw new CopyPropertyException("数据源为空");
}
//建立一个集合,用于存储目标对象,所有数据抓换完成后,将该集合返回
List targetList =Lists.newArrayList();
//循环取到单个源对象
for(T t : source) {//获取源对象的类的详情信息
Class> sClass =t.getClass();//获取源对象的全部属性
Field[] sFields =sClass.getDeclaredFields();//获取目标对象的全部属性
Field[] tFields =tClass.getDeclaredFields();
E target;try{//经过类的详情信息,建立目标对象 这一步等同于UserTwo target = new UserTwo();
target =tClass.newInstance();
}catch(Exception e) {
e.printStackTrace();throw new CopyPropertyException("目标对象建立失败");
}
//循环取到源对象的单个属性
for(Field sField : sFields) {//循环取到目标对象的单个属性
for(Field tField : tFields) {
//判断源对象的属性名、属性类型是否和目标对象的属性名、属性类型一致
if(sField.getName().equals(tField.getName()) &&sField.getGenericType().equals(tField.getGenericType())) {
try{//获取源对象的属性名,将属性名首字母大写,拼接如:getUsername、getId的字符串
String sName =sField.getName();char[] sChars =sName.toCharArray();
sChars[0] -= 32;
String sMethodName= "get" +String.valueOf(sChars);//得到属性的get方法
Method sMethod =sClass.getMethod(sMethodName);//调用get方法
Object sFieldValue =sMethod.invoke(t);
//获取目标对象的属性名,将属性名首字母大写,拼接如:setUsername、setId的字符串
String tName =tField.getName();char[] tChars =tName.toCharArray();
tChars[0] -= 32;
String tMethodName= "set" +String.valueOf(tChars);//得到属性的set方法
Method tMethod =tClass.getMethod(tMethodName, tField.getType());//调用方法,并将源对象get方法返回值做为参数传入
tMethod.invoke(target, sFieldValue);
break;
}catch(Exception e) {
e.printStackTrace();throw new CopyPropertyException("转换失败,请检查属性类型是否匹配");
}
}
}
}//将经过反射建立的目标对象放入集合中
targetList.add(target);
}//返回集合
returntargetList;
}
}