【Java】数组对象转实体对象

使用说明
使用时,要留意Object数组中值的顺序,需要与目标实体类中构造方法的形参的顺序保持一致,防止出现赋值错误的情况。

工具类代码

/**
 * 数据类型转换工具类
 * @author xupeng
 */
public class DataConvertUtil {

    /**
     * Object[] 转 Java Bean
     * @param objectArray 原数组
     * @param clazz 目标 Bean
     * @param <T>
     * @return
     */
    public static <T> T objectArrayToBean(Object[] objectArray, Class<T> clazz) throws Exception {
        if (objectArray == null || objectArray.length == 0){
            return null;
        }
        Class<?>[] tClass = null;
        Constructor<?>[] constructors = clazz.getConstructors();
        for (int i = 0; i < constructors.length; i++){
            Constructor<?> constructor = constructors[i];
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (parameterTypes.length == objectArray.length){
                tClass = parameterTypes;
                break;
            }
        }
        return clazz.getConstructor(tClass).newInstance(objectArray);
    }
}

测试代码
准备一个实体类
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Student {
    private Long id;
    private String name;
}

main方法调用
public static void main(String[] args) throws Exception {
	Object [] a = new Object[]{1L,"张三"};
	Student student = DataConvertUtil.objectArrayToBean(a, Student.class);
	if (student != null){
	    System.out.println(student);
	}
}

 

posted @ 2022-11-04 17:36  xiexie0812  阅读(434)  评论(0编辑  收藏  举报