英文:
How to make calling a method dynamic with a 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();"
}
BigDecimal qMidRate = null;
for(MonthlyRates bar: results){
qMidRate = getoption;
//更多逻辑
}
我正在尝试从get方法中获取一个BigDecimal值,有没有办法做到这一点?任何帮助将不胜感激。
英文:
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.
答案1
得分: 1
如果所有这些方法都返回字符串,只需去掉双引号:
case 3:
getoption = bar.getOneMonth();
break;
case 4:
getoption = bar.getTwoMonth();
break;
case 5:
getoption = bar.getThreeMonth();
break;
英文:
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;
答案2
得分: 0
你可以在使用Java 8时使用方法引用/lambda来完成这个。类似于:
// 我不清楚'getOneMonth'等是返回什么或者有什么参数...
// 这里假设它们接受一个Long参数,返回一个String,因为我不确定。
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());
}
注意:由于你要求只返回翻译好的部分,因此我只提供了代码的翻译部分。
英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论