Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

4 Answers

up vote 3 down vote accepted

In groovy you can do:

Myclass.(myArray[0])()

In Java you can do:

MyClass.class.getMethod(myArray[0]).invoke(null);
share|improve this answer
1  
Hallelujah! I'm so glad I am using groovy. That's exactly what I was trying to do. – Kyle Weller Dec 24 '12 at 16:10
And on your java example, what is the null for when you invoke the method? – Kyle Weller Dec 24 '12 at 16:12
1  
Normally you want to execute methods on objects. In this case you have to pass the object you want to use. But in your example you are using static methods so no object is needed. Thats why null is passed to the invoke method. – micha Dec 24 '12 at 16:14
@micha, why println Myclass.(myArray[0])() works but myArray.each { println Myclass.(it)() } doesn't? – Will P Dec 24 '12 at 17:10
1  
Hm good question, I am not sure. MyClass.(it.toString())() works – micha Dec 24 '12 at 17:19

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

myArray.each {
  println Myclass."$it"()
}
share|improve this answer

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);
share|improve this answer

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 loob
Method method = cl.getDeclaredMethod("/* methodName */", params);
method.invoke(obj, null);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.