两个实体属性一致,拷贝使用getConstructor方法
protected E createEntity(Class<E> entityClz,Class<T> dtoClz,T record) {
E entity = null;
try {
entity = entityClz.getConstructor(dtoClz).newInstance(record);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return entity;
}
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
com.wisdom.app.service.common.util.BeanUtils.copyProperties(dest, orig);
}
/**
* @param sourceObj
* @param targetClass
* @param <T>
* @return
*/
public static <T> T copyObject(Object sourceObj, Class<T> targetClass) {
if (sourceObj == null) {
return null;
}
T target = null;
try {
target = targetClass.newInstance();
BeanUtils.copyProperties(sourceObj, target);
} catch (Exception e) {
logger.error("convert error. msg={}", e.getMessage());
}
return target;
}
/**
* @param sourceList
* @param targetClass
* @param <T>
* @return
*/
public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {
if (sourceList == null) {
return null;
}
List targetList = new ArrayList(sourceList.size());
try {
for (Object obj : sourceList) {
T target = targetClass.newInstance();
BeanUtils.copyProperties(obj, target);
targetList.add(target);
}
} catch (Exception e) {
logger.error("convert error. msg={}", e.getMessage());
}
return targetList;
}
获取类的属性对象,getDeclaredFields用于获取方法,属性
(1)获取注解对象:(ExportExcelAnnota类是自定义注解类)
//可以获取这个类的注解对象,可以用于excel注解导出
public static List<ExportExcelAnnota> getColumnNames(List<ExportExcelAnnota> columnNames, Class<?> targetClass){
if(CollectionUtils.isEmpty(columnNames)){
columnNames = new ArrayList<>();
}
//获取类的属性对象
Field[] fields = targetClass.getDeclaredFields();
for(int i=0;i<fields.length;i++){
ExportExcelAnnota api = fields[i].getAnnotation(ExportExcelAnnota.class);
if(api != null){
columnNames.add(api);
}
}
return columnNames;
}
(2)获取属性名数组
/**
* 获取属性名数组,得到类对象的属性名数组
* */
private static String[] getFiledName(Class<?> targetClass){
Field[] fields = targetClass.getDeclaredFields();
String[] fieldNames=new String[fields.length];
for(int i=0;i<fields.length;i++){
fieldNames[i]=fields[i].getName();
}
return fieldNames;
}
(3)根据属性名获取属性值
/**
* 根据属性名获取属性值
* @param fieldName
* @param o
* @return
*/
private static Object getFieldValueByName(String fieldName, Object o) {
try {
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;
} catch (Exception e) {
return null;
}
}