Search code examples
javareflectionintrospection

Find a PropertyDescriptor recursively using Reflection in Java


Is there anyway to find a property descriptor recursively using Java reflection?

Imagine a scenario where a User class has a field called profile, which itself is another class which has the email attribute.

By having the user object, I need to have access to profile.email so the desirable method signature should be something similar to this:

public PropertyDescriptor findPropertyDescriptor(Class<?> clazz, String path)
{
    // Code!
}

And the call would be something like:

findPropertyDescriptor(User.class, "profile.email")

I'm also thinking that calls like below should be possible as well:

findPropertyDescriptor(User.class, "addresses[2].postCode")

Solution

  • Since nobody has come up with a solution, I have to answer my question here.

    Thanks to Spring, this has been already implemented:

    public static <T> PropertyDescriptor getPropertyDescriptor(T rootObject, String path)
    {
        BeanWrapperImpl wrapper = new BeanWrapperImpl(rootObject);
        return wrapper.getPropertyDescriptor(path);
    }
    

    In addition to the requirement, mentioned in the question, it also supports Maps.