Java 实现map属性注入生成对象

94 阅读1分钟

Java map属性注入生成对象

  • 抽象类
package com.youlingdada.utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * 类反射操作成员属性工具类
 * @param <T>
 */
public abstract class Convert<T> {

    /**
     * 获取泛型具体class类型对象
     * @return 泛型具体class类型
     */
    private Class<T> getRealClassType(){
        // 获取父对象的泛型参数列表,该方法只能子类调用
        Type type = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) type;;
        return (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }

    /**
     * 通过map注入属性值,并返回一个对象实例
     * @param map 参数值
     * @return 实例对象
     */
    public T mapConvertObject(Map<String, Object> map) {
        try {
            // 创建一个实例
            Class<T> targetClass = getRealClassType();
            T instance = targetClass.newInstance();
            // 获取成员变量
            Field[] fields = targetClass.getDeclaredFields();
            for (Field field : fields) {
                // 获取成员变量名称
                String fieldName = field.getName();
                // 设置可进入,即可以注入值
                field.setAccessible(true);
                // map取出数据,注入实例
                if (map.containsKey(fieldName)){
                    field.set(instance, map.get(fieldName));
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 直接传入指定的class对象,map注入值,返回其实例
     * @param map 参数值
     * @param targetClass 指定的类对象
     * @return 实例对象
     */
    public T mapConvertObject(Map<String, Object> map, Class<T> targetClass){
        try {
            T instance = targetClass.newInstance();
            Field[] fields = targetClass.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                field.setAccessible(true);
                Object o = map.get(fieldName);
                field.set(instance, o);
            }
            return instance;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}
  • 例子 User实体类
package com.youlingdada.utils.entity;


import com.youlingdada.utils.Convert;

/**
* 这是继承了 Convert就可以生成使用map属性生成对应的java对象
*/
public class User extends Convert<User> {
    private String uId;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "uId='" + uId + ''' +
                ", username='" + username + ''' +
                ", password='" + password + ''' +
                '}';
    }
}