Java 中 Switch Case 的替代方案

2022-01-20 00:00:00 conditional-statements java

除了看起来不太好的 if else 之外,还有其他方法可以在 Java 中实现 switch case.一组值会组合在一起,根据选择需要执行相应的方法.

Is there any alternative way to implement a switch case in Java other than if else which is not looking good. A set of values will be there in combination, according to the selection corresponding method has to be executed.

推荐答案

大概你正在努力满足 case 保持不变的要求.通常这是一种代码气味,但您可以做一些事情.您可能想提出并链接到另一个详细说明您尝试转换的问题的问题.

Presumably you're struggling with the requirement of case's being constant. Typically this is a code-smell, but there are things you can do. You might want to raise and link to another question that details why you're trying to switch.

Map<String,Object> map = new HasMap<String,Object>();
// ... insert stuff into map
// eg: map.add("something", new MyObject());

String key = "something";
if (map.contains(key)) {
    Object o = map.get(key);
}

在上面的示例中,您可能希望映射到处理程序",例如

In the example above, you might want to map to 'handlers', something like

interface Handler {
    public void doSomething();
}

然后这一切都变成了查找.

which then makes this all turn into a lookup.

if (map.contains(key)) { map.get(key).doSomething(); }

再次,它有点味道,所以请发布一个说明推理的问题.

Again, it's a bit of a smell, so please post a question which illustrates the reasoning.

相关文章