首页 > 解决方案 > 如何使用 Switch Case-Java 动态调用方法

问题描述

我想调用一个方法。根据参数,将调用某个方法。目前我正在尝试使用 Switch Case 来实现这一点,但我无法让它工作。

代码:

String getoption = null;
switch (rateIndex){

case 3:
    getoption = "bar.getOneMonth();"
case 4:
    getoption = "bar.getTwoMonth();"
case 5:
    getoption = "bar.getThreeMonth();"

}

Big Decimal qMidRate = null;

for(MonthlyRates bar: results){
    qMidRate = getoption;  
    //more logic 
}


我正在尝试从 get 方法中获取 Big Decimal 值,有没有办法做到这一点?任何帮助,将不胜感激。

标签: javafor-loopmethodsswitch-statement

解决方案


如果所有这些方法都返回字符串,只需去掉双引号:

case 3:
    getoption = bar.getOneMonth();
    break;
case 4:
    getoption = bar.getTwoMonth();
    break;
case 5:
    getoption = bar.getThreeMonth();
    break;

推荐阅读