Invoking all setters within a class using reflection
Solution 1
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?
Solution 2
Have you tried BeanUtils.populate()
) from Apache Commons BeanUtils?
BeanUtils.populate(yourObject, propertiesMap);
user1383163
Updated on June 25, 2022Comments
-
user1383163 almost 2 years
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.