1

我在逻辑上试图弄清楚我将如何做到这一点时遇到了麻烦。我可能会采取完全错误的方法。我将提供的这个例子是我想要的,但我知道它现在完全有缺陷,并且不确定我是否可以添加某种类型的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
 }

提前致谢。

4

3 回答 3

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
  }
}
于 2013-05-24T13:01:33.273 回答
3

好的,根据您在 Quetzalcoatl 的回答中的评论,这是我的回答

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

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

所以你的方法就像

method1()method2()

于 2013-05-24T13:21:00.170 回答
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);
于 2013-05-24T13:01:56.710 回答