List<Emp> empLists=list;//数据集合
ConvertEntity<Emp, Employee> entity=new ConvertEntity<Emp, Employee>(Emp.class, empLists, null, new Emp(), Employee.class, new Employee());
List<Employee> employeeList=entity.convertToEbs();
package com.aa.finance.ebs.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 对象转换
* @author aa
* @param <T>
* @param <V>
*/
public class ConvertEntity<T,V> {
private static final Logger logger = LoggerFactory.getLogger(ConvertEntity.class);
Class<T> clazz;
List<T> list;
String param;
T t;
V v;
Class<V> clavv;
public ConvertEntity(Class<T> clazz,List<T> list,String param,T t,Class<V> clavv,V v) {
this.clazz=clazz;
this.list=list;
this.param=param;
this.t=t;
this.v=v;
this.clavv=clavv;
}
/**
* 对象赋值
* @param list
* @return
*/
public List<V> convertToEbs() throws Exception{
List<V> infos=new ArrayList<>();
for (T t : list) {
V v=clavv.newInstance();
Field[] fieldsEbs = clavv.getDeclaredFields();//范型实例化
Field[] fields=clazz.getDeclaredFields();
for (Field field : fields) {
for (Field fieldEbs : fieldsEbs) {
if(fieldEbs.isAnnotationPresent(AnnotationForEbs.class)){
AnnotationForEbs fieldAnno = fieldEbs.getAnnotation(AnnotationForEbs.class);
if(fieldAnno.name().toString().equals(field.getName())){
String fileName=fieldEbs.getName().toString();
// 将属性的首字符大写
fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
String setMethodName = "set"+fileName;
//得到get方法的Method对象,带参数
// try {
Method setMethod = clavv.getDeclaredMethod(setMethodName,fieldEbs.getType());
setMethod.setAccessible(true);
Object object=getFieldValueByName(field.getName(), t);
setMethod.invoke(v,object);
}
}
}
}
infos.add(v);
}
return infos;
}
/**
* 根据属性名获取属性值
*/
private static Object getFieldValueByName (String fieldName, Object o)throws Exception {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
}
}
package com.aa.finance.bb.biz.entity.mysql;
public class Employee {
@AnnotationForEbs(name="empId")
private String employeeId;
}
package com.aa.finance.bb.biz.entity.mysql;
public class Emp {
private String empId;
//get set方法
}
package com.aa.finance.bb.util;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnnotationForEbs {
/** 对应的列名称 */
String name() default "";
}