【问题标题】:Using a while loop to call a method based on the argument received?使用while循环根据收到的参数调用方法?
【发布时间】:2013-05-20 02:05:04
【问题描述】:

我在逻辑上试图弄清楚我将如何做到这一点时遇到了麻烦。我可能会采取完全错误的方法。我将提供的这个示例是我想要的,但我知道它现在完全有缺陷,并且不确定是否可以添加某种类型的 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。逻辑将在 3 处停止 while 循环,但如果我的方法如下,我将在 if statement 中使用什么:

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

提前致谢。

【问题讨论】:

  • 问题不够清楚..你到底想执行什么..用清楚的话告诉我们
  • 看来需要用java反射来探索一下:docs.oracle.com/javase/tutorial/reflect
  • @StinePike 这么粗鲁有什么意义?当然,我仍在发现新事物,而且我还没有深入研究 Java,但我还在上高中,我只是想找到一种精简的方法来运行大约十几种方法中的一种,基于通过了什么论据。我要标记你的粗鲁和冒犯。不过,感谢您抽出时间发表您的意见。
  • @user2388169 .. 对不起我的最后评论.. 不想伤害你.. 我为我的误解道歉。 ..欢呼

标签: java if-statement methods while-loop


【解决方案1】:

在我看来,您尝试实现自己版本的 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
  }
}

【讨论】:

  • 这看起来和我需要的完全一样,但我的问题是,可能会有几十个case。有没有更简洁的方法来实现这一点?
【解决方案2】:

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

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

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

所以你的方法会像

method1()method2()

【讨论】:

    【解决方案3】:

    蛮力回答:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 2013-12-22
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多