Search code examples
javareflectionjavabeans

How do I get a Method of a nested property?


I have a class Foo that a property of the type Bar.

public class Foo {
    public Bar getBar() {

    }
}

public class Bar {
    public String getName();
}

Is there a helper class or method that gets you a java.lang.reflect.Method object of the name property of Bar, using Foo.class and "bar.name"?

There is a class called PropertyUtils in Commons BeanUtils, but its getPropertyDescriptor() only works for Object instances, not Class instances.

I realize it's not hard at all to implement one, but I'd like to leverage what's already available.

Also, the fact that I need a Method object is not a result of bad design(hope not). What I'm working on is pretty much a JavaBeans editor.

Thanks!


Solution

  • In Commons BeanUtils, PropertyUtils.getPropertyDescriptors() takes a Class as input and returns an array of PropertyDescriptor.

    I don't know if it will return "nested" names such as bar.name but if not, it shouldn't be too hard to recurse on the result and construct your own list of nested names.

    Just a quick sanity check though... does the world really need yet another JavaBeans editor?