0

The following SO post shows very nicely how to use introspector to list the getters associated with a class.

Java Reflection: How can i get the all getter methods of a java class and invoke them

The code I am using from this post is:

for(PropertyDescriptor propertyDescriptor : 
  Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
  System.out.println(propertyDescriptor.getReadMethod());          
}

This works fine for my 'User' class, with the output being:

public java.lang.String com.SingleEntity.mind_map.User.getName()
public int com.SingleEntity.mind_map.User.getNumber_of_entries()
public java.lang.String com.SingleEntity.mind_map.User.getUser_created_date()

My question now is, how do I now invoke those methods? If this is explained somehow in the linked SO I apologise but I don't understand it and would really appreciate an example.

Naturally I know how to invoke a Class method normally, but the assumption here is that the getters are unknown to the program until the above code discovers them.

Community
  • 1
  • 1
Single Entity
  • 2,925
  • 3
  • 37
  • 66

1 Answers1

1

PropertyDescriptor.getReadMethod() returns a Method object.

Simply use Method.invoke(Object instance, Object... args).

Something in the lines of...

for(PropertyDescriptor propertyDescriptor : 
Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
    try {
        Object value = propertyDescriptor
                       .getReadMethod()

               .invoke(myUserInstance, (Object[])null);      
    }
    catch (IllegalAccessException iae) {
        // TODO
    }
    catch (IllegalArgumentException iaee) {
        // TODO
    }
    catch (InvocationTargetException ite) {
        // TODO
    }
}
Mena
  • 47,782
  • 11
  • 87
  • 106