假设我有一个performActions
值为“openURL”和“closeBrowser”的数组列表。这些值(openURL 和 closeBrowsers)和方法都在不同的类中。
如何通过从performActions
arraylist 获取值来调用这些方法?
具体来说:如果我这样做performAction.get(0)
,应该执行“openURL”方法。
假设我有一个performActions
值为“openURL”和“closeBrowser”的数组列表。这些值(openURL 和 closeBrowsers)和方法都在不同的类中。
如何通过从performActions
arraylist 获取值来调用这些方法?
具体来说:如果我这样做performAction.get(0)
,应该执行“openURL”方法。
不,没有简单的方法来做你描述的事情(你可以使用反射,但我建议不要这样做)。但是,您可以存储一组整数,然后将这些整数用作执行各种功能的“代码”。这有点类似于存储方法本身。
public void runMethod(int n) {
switch (n) {
case 1:
// do something (e.g. run a certain method)
break;
case 2:
// do something else (e.g. run another method)
break;
...
}
}
所以在你的情况下,openURL
也许可以用和1
表示(你当然可以使用任何两个整数)。然后,您将这些值存储在一个 中,之后您将遍历您的列表并在每个值上调用类似的方法,从而执行您想要的方法。closeBrowser
2
ArrayList<Integer>
runMethod
编辑:如果您的方法需要一个参数,您总是可以使用类似的概念,使用Map
s 而不是ArrayList
s,将整数(表示方法)映射到其参数。
我会保持简单并使用字符串比较来执行您的方法:
List<String> items; // from Excel
for (String item : items) {
// for example, item might be: openURL("www.google.com")
if (item.startsWith("openURL(")) {
// parse out the actual url
String url = item.replaceAll(".*\"(.*)\".*", "$1");
openURL(url);
} else if (item.startsWith("closeURL(")) {
// etc
}
}
使用反射。
例如:方法方法 = getClass().getMethod(yourarraylist.get(0)); 方法.invoke(this);
这类似于我们在加载 jdbc 驱动程序时所做的事情 class.forName();
我建议阅读有关反思的内容。Hipe 这有帮助:-)
假设ArrayList
包含Method,并且该方法是静态的,您可以使用Method.invoke(null, null)
如果方法引用不是静态的,那么您需要提供一些上下文才能执行它。
我会将要在包装类中执行的 and 包装起来,并提供一个调用/执行方法Method
...Object
public class ProxyMethod {
private Method method;
priavte Object instance;
public ProxyMethod(Object instance, Method method) {
this.instance = instance;
this.method = method;
}
public void invoke() {
method.invoke(this, null);
}
}
现在您还可以提供参数,如果您需要...
public class ProxyMethod {
// Previous decelerations...
private Object[] parameters;
public ProxyMethod(Object instance, Method method, Object... parameters) {
this(instance, methd);
this.parameters = parameters;
}
public void invokeWith() {
method.invoke(this, parameters);
}
public void invokeWith(Object... parameters) {
method.invoke(this, parameters);
}
我会使用脚本语言: