Alternative to Switch Case in Java(Java 中 Switch Case 的替代方案)
问题描述
除了看起来不太好的 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.
这篇关于Java 中 Switch Case 的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 中 Switch Case 的替代方案


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01