Invoking all setters within a class using reflection

invoke, java, reflection

Solution

Sure it's possible! You can get all methods that start with "set" back by doing this:

Class curClass = myclass.class;
Method[] allMethods = curClass.getMethods();
List<Method> setters = new ArrayList<Method>();
for(Method method : allMethods) {
    if(method.getName().startsWith("set")) {
        setters.add(method);
    }
}

Now you've got the methods. Do you already know how to call them for your instance of the class?

Problem

I have a domain object, that for the purposes of this question I will call Person with the following private variables: ``` String name int age ``` Each of these have getters and setters. Now I also have a `Map<String, String>` with the following entries: ``` name, phil age, 35 ``` I would like to populate a list of all setter methods within the class Person and then looping through this list and invoking each method using the values from the map. Is this even possible as I cannot see any examples close to this on the net. Examples are very much appreciated.

Original source