可以用for做getMethodX吗? [英] Is it possible to do getMethodX with a for?
本文介绍了可以用for做getMethodX吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有四个方法如此创建:
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.
Java 8中的替代方法是这样做
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();
这篇关于可以用for做getMethodX吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文