Last Updated: February 25, 2016
·
1.292K
· kaqqao

Avoid direct reflection code with the help of Spring

A neat way to avoid dealing with reflection directly in some usual scenarios is to use Spring's PropertyAccessorFactory.
For example, given the bean:

public class NiceBean {
    public String value = "default";

    public String getValue() {
        return "calculated";
    }
}

it is easy to get the correct value reflectively by calling PropertyAccessorFactory.forBeanPropertyAccess(new NiceBean()).getPropertyValue("value").

Of course, avoiding reflection altogether is by far the best approach, but when it is required, this is a nice way not to have to deal with the ugly reflection code directly. Alas, it seems private fields can not be read in this fashion. For that and other more complex cases, take a peek into Spring's ReflectionUtils class.