使用反射调用类中的所有设置器 [英] Invoking all setters within a class using reflection

查看:89
本文介绍了使用反射调用类中的所有设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个域对象,出于这个问题的目的,我将使用以下私有变量调用Person:

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

每个都有吸气剂和吸气剂.现在,我还有一个Map<String, String>,其中包含以下条目:

Each of these have getters and setters. Now I also have a Map<String, String> with the following entries:

name, phil
age, 35

我想填充Person类中所有setter方法的列表,然后循环浏览此列表,并使用映射中的值调用每个方法.

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.

推荐答案

当然可以!通过执行以下操作,您可以获得以"set"开头的所有方法:

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?

这篇关于使用反射调用类中的所有设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆