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

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

java - Invoking all setters within a class using reflection

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

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

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...