4

在 Java 或 Groovy 中,假设我有一个类似的字符串数组

myArray = ["SA1", "SA2", "SA3", "SA4"]

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

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

我希望能够遍历我的数组并调用它们相关的函数,而无需比较字符串或进行 case 语句。例如,有没有一种方法可以执行以下操作,我知道它目前不起作用:

Myclass[myArray[0]]();

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

4

4 回答 4

3

在 groovy 中,您可以执行以下操作:

Myclass.(myArray[0])()

在 Java 中,您可以执行以下操作:

MyClass.class.getMethod(myArray[0]).invoke(null);
于 2012-12-24T16:06:41.173 回答
3

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

myArray.each {
  println Myclass."$it"()
}
于 2012-12-24T17:15:22.097 回答
2

You can, for instance, declare an interface such as:

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

then implement this interface, for example in singletons.

Then create a Map<String, Processor> where keys are your strings, values are implementations and, when invoking:

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

p.process(theString);
于 2012-12-24T16:01:41.640 回答
0

I suggest you look at Reflection APIs, to call methods at runtime check 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);
于 2012-12-24T16:03:19.703 回答