0

这是我的情况,我不知道是否可能,我需要一些想法。

我的 MasterTable 对象填充了数据

MasterTable MT; //already with data

方法列表

List<String> mymethods = new ArrayList<String>();
mymethods.add("getName");
mymethods.add("getLocation");

我有一个数组 MasterTable 方法,

Class<MasterTable> masterclass = MasterTable.class;
Method[] masterMethods = masterclass.getMethods();

我想要的是遍历 MasterTable 方法,当我找到匹配我的标准的 masterMethod 时,我打印该方法的值。

例如

for (Method mm : masterMethods) {
if(mymethods.contains(mm.getName)){
      //print method matching MT.get Method Matching mm.getName
      System.out.println("print MT.getMethodMatchingmm.getName()");
}
}

是否有可能做到这一点?

4

1 回答 1

1

当然!

if (mymethods.contains(mm.getName()) {
    Object result = mm.invoke(MT);
    // do anything with result
}

我已经尝试过相反的方法,以避免重载方法的不需要的匹配:

public static void callGetters(Object instance, String... names)
        throws Exception {
    for (String name : names) {
        Method method = instance.getClass().getMethod(name);
        System.out.println(name + ": " + method.invoke(instance));
    }
}

/**
 * @param args
 */
public static void main(String[] args) throws Exception {
    callGetters(new MyObject(), "getName", "getLocation");
}
于 2013-09-26T11:19:28.267 回答