Java教程

java List<Object[]>转Class<T> clz对象

本文主要是介绍java List<Object[]>转Class<T> clz对象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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);

                    
这篇关于java List<Object[]>转Class<T> clz对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!