使用BeanUtils检索字段值 [英] Retrieve field values using BeanUtils

查看:280
本文介绍了使用BeanUtils检索字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取未由某些自定义注释标记的私有字段值,这可以通过BeanUtils吗?如果是,怎么办?

I want to extract private field values that are not marked by certain custom annotation, is this possible via BeanUtils? If yes, how?

推荐答案

否,BeanUtils无法实现.但是您可以使用Java自己的反射工具,如下所示:

No, it is not possible with BeanUtils. But you can use Java's own reflection tools like this:

public class BeanUtilTest {
    public static void main(String[] args) throws ... {
        MyBean bean = new MyBean();

        Field field = bean.getClass().getDeclaredField("bar");
        field.setAccessible(true);
        System.out.println(field.get(bean));
    }

    public static class MyBean {
        private final String bar = "foo";
    }
}

请考虑:使用反射访问私有字段是非常糟糕的样式,应仅在测试时确定,或者如果您确定没有其他方法,则应这样做.如果您没有能力更改要尝试访问的类的源,则可能是不得已的选择.但是请考虑一下,这种行为将来可能会改变(例如,作为您正在使用的库的更新)并破坏您的代码.

Please consider: Accessing private fields with reflection is very bad style and should be done only for tests or if you are sure there is no other way. If you don't have the ability to change the sources of the class you're trying to access, it might be a last resort. But consider that the behavior might change in the future (e.g. as an update of the library you're using) and break your code.

编辑:如果BeanUtils或PropertyUtils正常工作,则意味着该属性有一个公共的吸气剂,您应该使用它而不是使用反射.在没有公共获取器的私有字段上使用PropertyUtils会引发NoSuchMethodException.

If BeanUtils or PropertyUtils are working, this means there is a public getter for this property and you should be using it instead of using reflection. Using PropertyUtils on a private field without a public getter throws a NoSuchMethodException.

这篇关于使用BeanUtils检索字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆