java - 使用反射代替长 switch 语句

标签 java performance memory reflection switch-statement

嘿,我有一个很长的 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/

相关文章:

java - 尝试调用 Watson Translation Service

python - 应用其参数取决于列值的函数

java - PostgreSQL 连接的内存使用量在执行中不断增加

C++ : terminate called after throwing an instance of 'std::bad_alloc' while computing length of big strings

android - 如何从内存中清除动态创建的 View ?

java - 在Java中播放音频文件

java - twitter4j.TwitterException : 401:Authentication credentials were missing or incorrect

Java servlet - session 清理 (HttpServletRequest)

c++ - vector::clear() 花这么多时间?

jQuery(中)高效使用