Call a function from a string array (Java or Groov

2019-04-10 00:56发布

In Java, or Groovy, say I have a String array like

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

I want to call a different function based off of each string.

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

I would love to be able to loop through my array and call the functions that they pertain to without having to compare the string or make a case statement. For example is there a way to do something like the following, I know it doesn't currently work:

Myclass[myArray[0]]();

Or if you have suggestions of another way I can structure something similar.

4条回答
唯我独甜
2楼-- · 2019-04-10 01:29

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);
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-10 01:31

In Groovy, you can use a GString for dynamic method invocation:

myArray.each {
  println Myclass."$it"()
}
查看更多
Ridiculous、
4楼-- · 2019-04-10 01:33

In groovy you can do:

Myclass.(myArray[0])()

In Java you can do:

MyClass.class.getMethod(myArray[0]).invoke(null);
查看更多
Root(大扎)
5楼-- · 2019-04-10 01:46

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);
查看更多
登录 后发表回答