简体   繁体   中英

How to make calling a method dynamic with a Switch Case- Java

I want to call a method. Depending on a argument a certain method will be called. Currently I am trying to achieve this using a Switch Case, but I cant get it to work.

Code:

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 
}


I am trying to get a Big Decimal value from the get methods, is there any way of doing this? any help would be appreciated.

If all those methods are returning strings, simply ditch the double quotes:

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

You can do this with method references/lambdas if you're using java 8. Something like:

    // I have no idea what 'getOneMonth', etc. are returning or have as parameters...
    // This assumes they take a Long, and return a String, 'cause I don't know.
    Function<Long, String> choice = null;
    switch (rateIndex) {
        case 3:
            choice = bar::getOneMonth;
            break;
        case 4:
            choice = bar::getTwoMonths;
            break;
        // ...
        default:
            throw new HissyFit();
    }

    for (final MonthlyRates rates : bar.getMonthlyRates()) {
        final String methodCallResult = choice.apply(rates.getSomeLong());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM