I have four method so created:
method1();
method2();
method3();
method4();
Can I use it like this?
for (int i = 1; i <= 4; i++) {
method+i+(); // ?
}
I have four method so created:
method1();
method2();
method3();
method4();
Can I use it like this?
for (int i = 1; i <= 4; i++) {
method+i+(); // ?
}
There is a number of ways to do this but in general it suggests you haven't structured you program correctly. You can do this.
for (int i = 1; i <= n; i++)
getClass().getMethod("method" + i).invoke();
Or you could just have a long method which combines all the functionality you need.
An alternative in Java 8 is to do this
Runnable[] runs = {
this::methodOne,
this::methodTwo,
this::methodThree,
this::methodFour,
this::methodFive,
this::methodSix };
for (int i = 0; i < n; i++)
runs[i].run();
You can user Reflection for doing so but it is somewhat awful.
Class<TheClassThatHasSuchMethods> clazz = this.getClass();
for (int i=0; i < 4; i++) {
Method method = clazz.getMethod("method" + i);
method.invoke(this);
}
Be ready for handling a ton of exceptions
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
.
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.
You can use reflection. Reflection is tricky and doesn't perform well, so you should think about whether or not this is how you really want to proceed.
However, the code would look like
for (int i = 1 ; i <= 4; i++) {
Method method = this.getClass().getDeclaredMethod("method"+i);
method.invoke(this);
}
assuming the methods are not static and are defined in the current class.