Cool
Cool
Published on 2022-04-06 / 24 Visits
0
0

java通过反射给指定字段赋值

/**
     * 反射给字段赋值
     * @param entity
     * @param map
     * @param <T>
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    public static  <T> T setfields(T entity,Map<String,Object> map) throws IllegalAccessException, NoSuchFieldException {
        Class<?> clazz = entity.getClass();

        for (String key : map.keySet()) {
            Object value = map.get(key);
            if (null==value){
                continue;
            }
            // 获取字段
            Field field = clazz.getDeclaredField(key);
            // 开通权限
            field.setAccessible(true);
            // 赋值
            field.set(entity,ConvertUtils.convert(map.get(key), field.getType()));
        }
        return entity;
    }

Comment