package com.xny.base.util;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
/**
* @author wuqs
* @version 1.0.0
* @ClassName ObjectToBeanUtils.java
* @Description List<Object[]>转换成一个List<T>
* @createTime 2021年11月29日 16:25:00
*/
public class ObjectToBeanUtils {
/**
* 把List<Object[]>转换成List<T>
*/
public static <T> List<T> objectToBean(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
for (Object[] obj : objList) {
Constructor<T> cr = clz.getConstructor(cz);
Object[] v = new Object[obj.length];
for(int i=0;i<obj.length;i++){
if(i == 0){
v[i] = obj[i];
}else{
v[i] = Double.valueOf(obj[i].toString());
}
}
list.add(cr.newInstance(v));
}
return list;
}
public static <T> List<T> objectToBeanTwo(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
for (Object[] obj : objList) {
Constructor<T> cr = clz.getConstructor(cz);
Object[] v = new Object[obj.length];
for(int i=0;i<obj.length;i++){
if(null == obj[i]){
v[i] = "";
}else{
v[i] = obj[i].toString();
}
}
list.add(cr.newInstance(v));
}
return list;
}
}
代码示例:
List<CdqUpEntityVo> list = ObjectToBeanUtils.objectToBean(objects, CdqUpEntityVo.class);