Java反射setAccessible(true)安全检查不通过

Bean转Map

public static Map<String, Object> beanToMap(Object object) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    Class cls = object.getClass();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        map.put(field.getName(), field.get(object));
    }
    return map;
}

上述代码使用了setAccessible(true)公司安全检查不通过

public static Map<String, Object> beanToMap(Object obj) {
    if (obj == null) {
        return null;
    }
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        logger.error("transBean2Map Error ", e);
    }
    return map;
}

使用这种方式,安全可靠

上一篇 Jackson实体为NULL或者为空不显示
下一篇 使用Java暴力搜索文件夹下所有包含指定字符串的文本文件
目录
文章列表
1 Linux下安装OpenResty
Linux下安装OpenResty
2
Swift - 使用arc4random()、arc4random_uniform()获取随机数
Swift - 使用arc4random()、arc4random_uniform()获取随机数
3
Flutter提示弹框
Flutter提示弹框
4
PHP中 HMAC-MD5 加密算法
PHP中 HMAC-MD5 加密算法
5
无需mapper.xml,MyBatis新特性动态SQL
无需mapper.xml,MyBatis新特性动态SQL
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。