If you're using Java 8, you can place method references into a Map
, and then access them by name.
Assuming your methods are in a class such as this:
public class Test
{
public void method1() { System.out.println("Method 1!"); }
public void method2() { System.out.println("Method 2!"); }
public void method3() { System.out.println("Method 3!"); }
public void method4() { System.out.println("Method 4!"); }
}
The key is the method name.
Map<String, Runnable> methodMap = new HashMap<String, Runnable>();
Test test = new Test();
methodMap.put("method1", test::method1);
methodMap.put("method2", test::method2);
methodMap.put("method3", test::method3);
methodMap.put("method4", test::method4);
for (int i = 1; i <= 4; i++)
{
String methodName = "method" + i;
Runnable method = methodMap.get(methodName);
method.run();
}
Output:
Method 1!
Method 2!
Method 3!
Method 4!
If your methods take some parameters and/or return a value, then you'll need to choose a different functional interface, different than Runnable
.
- Supplier or [Boolean|Int|Double|Long]Supplier to return a value without taking parameters.
- Consumer or [Boolean|Int|Double|Long]Consumer to take a parameter without returning a value.
- Various
Function
-like interfaces for taking a parameter and returning a function.
Failing that, you can always define your own functional interface that represents the parameter(s) and possible return value that fits your methods.