Retrieve field values using BeanUtils

16,089

Solution 1

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.

Solution 2

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

Share:
16,089
TheLameProgrammer
Author by

TheLameProgrammer

Updated on July 21, 2022

Comments

  • TheLameProgrammer
    TheLameProgrammer almost 2 years

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

  • Arnout Engelen
    Arnout Engelen over 12 years
    Wouldn't this yield a NoSuchMethodException for a field without a getter and a IllegalAccessException if there is a getter but it is not accessible? What if there's no public getter?