• Java之反射获取和赋值字段


    在Java中,反射能够使得代码更加通用,往往用于工具类中。
    但常常我们在获取或者赋值反射的属性时,会出现没有赋值成功的结果,往往是由于这个属性在父级中而导致的,这个时候我们就不能用getDeclaredField方法单独获取字段,而是循环遍历所有的父级取字段。

    下面提供获取所有属性方法(包括父级):

    
    /**
     * description: 从当前以及父类中获取全部字段
     *
     * @param clazz 属性所在类
     * @return java.lang.reflect.Field
     */
    public static List<Field> getFieldByCurrentAndSuper(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        getFieldByCurrentAndSuper(clazz, fields);
        return fields;
    }
    
    /**
     * description: 从当前以及父类中获取全部字段
     *
     * @param clazz 属性所在类
     * @return java.lang.reflect.Field
     */
    private static List<Field> getFieldByCurrentAndSuper(Class<?> clazz, List<Field> fields) {
        Field[] declaredFields = clazz.getDeclaredFields();
        fields.addAll(Arrays.asList(declaredFields));
        if (!clazz.equals(Object.class)) {
            return getFieldByCurrentAndSuper(clazz.getSuperclass(), fields);
        }
        return fields;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    我们拿到泛型的Class后,就可以直接调用getFieldByCurrentAndSuper方法来获取所有属性,然后遍历对属性操作,如下:

    /**
     * 深度赋值属性
     */
    private static void setField(Class<?> clazz, String userTenantCode, Object arg) throws IllegalAccessException {
        try {
            List<Field> fieldList = getFieldByCurrentAndSuper(clazz);
            if (fieldList.size() > 0) {
                for (Field field : fieldList) {
                    if (field.getName().equals("tenantCode")) {
                        // 设置可访问私有属性
                        field.setAccessible(true);
                        field.set(arg, userTenantCode);
                    }
                }
            }
        } catch (Exception ignored) {
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    ssh秘钥和python 虚拟环境
    nginx中deny和allow详解
    学信息系统项目管理师第4版系列10_变更管理与文档管理
    无代码开发smardaten与Power Platform详细对比
    玄机靶场 第一章 应急响应- Linux入侵排查
    服装连锁店铺管理软件大盘点!秦丝、日进斗金、商陆花谁更强?
    5年Java面试阿里P6经验总结
    springboot+jsp高校学生宿舍管理系统-宿管带前端
    java高级:注解
    Sentinel 流控注解使用
  • 原文地址:https://blog.csdn.net/jl15988/article/details/134509106