Call a function from an array of strings (Java or Groovy)

In Java or Groovy, let's say I have an array of strings like

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

I want to call another function based on each line.

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

I would like for me to be able to skip my array and call the functions to which they refer, without having to compare a string or make a case statement. For example, there is a way to do something like the following, I know that it currently does not work:

 Myclass[myArray[0]](); 

Or, if you have suggestions in a different way, I can create something similar.

+4
source share
4 answers

In groovy you can do:

 Myclass.(myArray[0])() 

In Java you can:

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

In Groovy, you can use GString to call a dynamic method:

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

You can, for example, declare an interface, for example:

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

then we implement this interface, for example, in single games.

Then create a Map<String, Processor> , where your lines are indicated, values ​​are implementations, and when called:

 Processor p = theMap.containsKey(theString) ? theMap.get(theString) : defaultProcessor; p.process(theString); 
+2
source

I suggest you take a look at the Reflection API, 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); 
0
source

All Articles