使用while循环根据收到的参数调用方法?

时间:2013-05-24 12:56:35

标签: java if-statement methods while-loop

我在逻辑上试图弄明白我是怎么做的。我可能会以完全错误的方式去做。我将提供的这个例子就是我想要的,但我知道它现在完全有缺陷,并且不确定我是否可以添加某种类型的List来帮助。

public int getNumber(int num){
  int counter;
  counter = 1;
  while (counter < 5){ // 5 because that's the number of methods I have
    if (num == counter){
      //CALL THE APPROPRIATE METHOD
    }
    counter++;
  }
}

我遇到的问题是:当然,方法是用他们的名字来称呼,而不是用任何数字。 如果收到的参数为3,我将如何调用方法3.逻辑会将while循环停在3,但如果我的方法如下,我将在if statement中使用什么:

public Object methodOne(){
  //actions
 }
public Object methodTwo(){
  //actions
 }
public Object methodThree(){
  //actions
 }
public Object methodFour(){
  //actions
 }
public Object methodFive(){
  //actions
 }

提前致谢。

3 个答案:

答案 0 :(得分:4)

在我看来,您已尝试实施自己版本的switch声明。

也许你应该尝试:

public int getNumber(int num) {
  switch(num) {
    case 1:
      //call method one
      break;
    case 2:
      //call method two
      break;
    //etc
    default:
      //handle unsupported num
  }
}

答案 1 :(得分:3)

好根据你在Quetzalcoatl的回答,这里的回答是我的回答

您可以使用java反射按名称调用方法。例如

public int getNumber(int num) {
            String methodName = "method" + num;
            Method n = getClass().getMethod(methodName);
            n.invoke(this);
}

所以你的方法就像

method1()method2()等。

答案 2 :(得分:0)

蛮力回答:

Object result;
switch(num){
    case 1: result = methodOne(); break;
    case 2: result = methodTwo(); break;
    case 3: result = methodThree(); break;
    case 4: result = methodFour(); break;
    case 5: result = methodFive(); break;
    default: result = null; break;
}

反思答案

static final String methodNames[] = { "methodOne", "methodTwo", "methodThree", 
        "methodFour", "methodFive" };

Object result = getClass().getMethod(methodNames[num - 1]).invoke(this);