如何动态调用Java Bean的方法。
我在 Java 类中有以下方法:
public class Bean {
public String column1val;
public String column2val;
public String column2val;
}
我需要从 for 循环访问这些方法,如下所示:
for(int i=0;i<2;i++) {
String s = Bean.get column+i+val;
}
我们怎样才能实现这个场景?
最佳答案
示例代码。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Bean {
public String getMethod1(String a) {
return a;
}
public String getMethod2(String a) {
return a;
}
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Bean bean = new Bean();
for (int i = 1; i <= 2; i++) {
Method method = Bean.class.getMethod("getMethod" + i, String.class);
System.out.println(method.invoke(bean, "Simple"));
}
}
}
关于java - 如何在for循环中动态调用Java Bean的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857430/