嘿,我有一个很长的 switch 语句,它调用基于这样的字符串的方法
private void callMethod(String name) {
switch(name) {
case "blah":
blah();
break;
case "method":
method()
break;
}
}
等等
所以我使用反射来缩短代码
try {
Method method = ClassName.class.getDeclaredMethod(name, args);
method.invoke(args);
} catch (NoSuchMethodException e) {
// switch default
}
只是想知道像这样使用反射是否会对内存/性能产生不良影响。我只是偶尔调用这个函数。
编辑:我使用它的原因是因为用户可以选择根据他们输入的字符串来启动游戏的不同部分。启动事件的每个方法都以他们需要输入的内容命名。
最佳答案
反射(reflection)通常是最糟糕的做事方式。它很慢,无法在运行时优化,并且编译器无法标记错误。正如 kpie 指出的,让用户输入直接控制执行哪个方法是一个安全漏洞。
任意长switch
语句可以用Map代替。在您的情况下, Map<String, Runnable>
就足够了:
Map<String, Runnable> actions = new HashMap<>();
actions.put("blah", this::blah);
actions.put("method", this::method);
// ...
Runnable action = actions.get(name);
if (action == null) {
throw new IllegalArgumentException("Invalid name: " + name);
}
action.run();
关于java - 使用反射代替长 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60311302/