Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...