从字符串数组(Java或Groovy)调用函数

时间:2012-12-24 15:58:42

标签: java reflection groovy

在Java或Groovy中,假设我有一个像

这样的String数组
myArray = ["SA1", "SA2", "SA3", "SA4"]

我想根据每个字符串调用不同的函数。

class Myclass{
  public static void SA1() {
    //doMyStuff
  }
  public static void SA2() {
    //doMyStuff
  }
  ...etc
}

我希望能够遍历我的数组并调用它们所属的函数,而无需比较字符串或创建case语句。例如,有没有办法做类似下面的事情,我知道它目前不起作用:

Myclass[myArray[0]]();

或者,如果您有其他方式的建议,我可以构建类似的东西。

4 个答案:

答案 0 :(得分:3)

在groovy中你可以做到:

Myclass.(myArray[0])()

在Java中你可以这样做:

MyClass.class.getMethod(myArray[0]).invoke(null);

答案 1 :(得分:3)

在Groovy中,您可以使用GString进行动态方法调用:

myArray.each {
  println Myclass."$it"()
}

答案 2 :(得分:2)

例如,您可以声明一个接口,例如:

public interface Processor
{
    void process(String arg);
}

然后实现此接口,例如在单身人士中。

然后创建一个Map<String, Processor>,其中键是你的字符串,值是实现,并且在调用时:

Processor p = theMap.containsKey(theString)
    ? theMap.get(theString)
    : defaultProcessor;

p.process(theString);

答案 3 :(得分:0)

我建议您查看Reflection API,以便在运行时调用方法 检查Reflection docs

Class cl = Class.forName("/* your class */");
Object obj = cl.newInstance();

//call each method from the loop
Method method = cl.getDeclaredMethod("/* methodName */", params);
method.invoke(obj, null);