Retrieve field values using BeanUtils

会有一股神秘感。 提交于 2019-12-23 12:13:08

问题


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


回答1:


Yes, assuming that you know the fields names. You can use PropertyUtils.getSimpleProperty(...). See also here for an example.




回答2:


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.

Edit: 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.



来源:https://stackoverflow.com/questions/6122432/retrieve-field-values-using-beanutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!