我创建了四种方法:
method1();
method2();
method3();
method4();
我可以像这样使用它吗?
for (int i = 1; i <= 4; i++) {
method+i+(); // ?
}
答案 0 :(得分:2)
有很多方法可以做到这一点,但总的来说,它表明你没有正确构建你的程序。你可以这样做。
for (int i = 1; i <= n; i++)
getClass().getMethod("method" + i).invoke();
或者您可以使用一个结合了所需功能的长方法。
Java 8中的替代方法是执行此操作
Runnable[] runs = {
this::methodOne,
this::methodTwo,
this::methodThree,
this::methodFour,
this::methodFive,
this::methodSix };
for (int i = 0; i < n; i++)
runs[i].run();
答案 1 :(得分:1)
您可以使用Reflection来执行此操作,但这有点糟糕。
Class<TheClassThatHasSuchMethods> clazz = this.getClass();
for (int i=0; i < 4; i++) {
Method method = clazz.getMethod("method" + i);
method.invoke(this);
}
准备好处理大量例外
答案 2 :(得分:1)
如果您使用的是Java 8,则可以将方法引用放入Map
,然后按名称访问它们。
假设你的方法属于这样的类:
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!"); }
}
键是方法名称。
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();
}
输出:
Method 1!
Method 2!
Method 3!
Method 4!
如果您的方法采用某些参数和/或返回值,那么您需要选择不同于Runnable
的不同功能界面。
Function
- 用于获取参数和返回函数的接口。如果做不到这一点,您可以随时定义自己的功能界面,该界面代表适合您方法的参数和可能的返回值。
答案 3 :(得分:0)
您可以使用反射。反思很棘手,并且表现不佳,所以你应该考虑这是否是你真正想要的方式。
但是,代码看起来像
for (int i = 1 ; i <= 4; i++) {
Method method = this.getClass().getDeclaredMethod("method"+i);
method.invoke(this);
}
假设方法不是静态的并且是在当前类中定义的。