问题
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