1

I want to get all the declared methods of a complex object. I have following classes

class Person {
    public String getName();
    public String getDesignation();
    public Address getAddress();
}

class Address {
    public String city;
    public String country;
}

Now when is use reflection

Person.class.getDeclaredMethod() 

given all the declared methods

getName, getDesignation, getAddress

Person.class.getMethods()

given all the methods in declared methods or the methods of super class

getName, getDesignation, getAddress, toString, waitFor

How can I get the methods of child classes as well when calling Person.class.getMethods()

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
Ambuj Jauhari
  • 1,187
  • 4
  • 26
  • 46
  • Note that `getMethods()` only returns **public** methods (implemented in child or parent class). – C.Champagne Jun 03 '16 at 16:27
  • One more thing, you cannot find directly the children classes from their parent (the class they extend) but you can find the parent class from a child....but I suspect that you consider `Address` as the child class. Am I wrong? – C.Champagne Jun 03 '16 at 16:35

1 Answers1

1

If you want all public methods of all superclasses, you will have to iterate over all superclasses (usually except java.lang.Object).

public static List<Method> getAllPublicMethods(Class<?> type){
  Class<?> current = type;
  List<Method> methods = new ArrayList<>();
  while(type!=null && type!= Object.class){
    Arrays.stream(type.getDeclaredMethods())
          .filter((m)-> Modifier.isPublic(m.getModifiers())
                    && !Modifier.isStatic(m.getModifiers()))
          .forEach(methods::add);
    type=type.getSuperclass();
  }
  return methods;

}

But if you are just interested in all getter methods, use the Introspector instead.

public static List<Method> getAllGetters(Class<?> type) {
  try {
    BeanInfo beanInfo = Introspector.getBeanInfo(type, Object.class);
    return Arrays.stream(beanInfo.getPropertyDescriptors())
                 .map(PropertyDescriptor::getReadMethod)
                 .filter(Objects::nonNull) // get rid of write-only properties
                 .collect(Collectors.toList());
  } catch (IntrospectionException e) {
    throw new IllegalStateException(e);
  }
}

For more info about the Introspector see this previous answer of mine.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • I am not interested in methods of super class, i am looking a way to get methods of Classes referenced inside the pojo that are forming contains a relations. like when i am trying to get methods of Person class, it should give me the list of methods of Address class as well – Ambuj Jauhari Jun 03 '16 at 16:55
  • That will get very complex fast because it involves nasty things like circular dependencies and primitive types. But in theory you can use the getters' return types and called the same method on them also – Sean Patrick Floyd Jun 03 '16 at 17:03