对我来说,if
-else if
太长而且难以阅读。
是否有一些表驱动的方法可以用来映射输入值以调用该值的特定方法?
例如:
for(String id:ids){
Test test = new Test();
if(id == "101") {
test.method1();
}else if(id=="102") {
test.method2();
}else if(id=="103"){
test.method3();
...
最佳答案
...
static Map<String,Method> methods = new HashMap<String,Method>();
...
static {
methods.put("101",Test.class.getMethod("method1",null));
methods.put("102",Test.class.getMethod("method2",null));
...
}
...
for( String id : ids ) {
Test test = new Test();
Method m = methods.get(id);
if (m != null) {
m.invoke(test,null);
}
}
当然,所有这一切真正做的是用 if/else 链的痛苦换取使用所有方法初始化散列的痛苦。
关于java - 如何在不使用 "if-else if"的情况下编写对不同参数使用不同方法的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22705062/