java - switch 语句或远程调用方法

标签 java reflection methods hashmap switch-statement

我有一个 switch 语句,它比较一个 String 和一组 String,其中每个匹配调用不同的方法。

switch(((Operation) expr.getData()).getValue()){
        case "+":
            return add(expr.getNext());
        case "car":
            return car(expr.getNext());
        case "cdr":
            return cdr(expr.getNext());
        case "cons":
            return cons(expr.getNext(), expr.getNext().getNext());
        case "quote":
            return quote(expr.getNext());
        case "define":
            handleDefine(expr.getNext());
            break;
        default:
            return null;
        }

但是,对我来说,这听起来像是可以使用链接到包含 Method 的 OperationHashMap 来更优雅、更高效地实现的事情 和参数的数量,这样我就可以将每个方法都变成一个 HashMap,例如:

nameToOperation.put("+", new Operation("+", 1, Driver.class.getMethod("add")));
nameToOperation.put("car", new Operation("car", 1, Driver.class.getMethod("car")));

所以会有 N 个不同的 Operation 类实例,每个实例都包含 String、Method 和参数数量

然后我可以简单地使用类似于此的方法调用该方法(我知道这不是您使用 invoke 的方式):

Operation op = ((Operation) expr.getData())

if(op.getNumPars() == 1)
    return(op.getMethod().invoke(expr.getNext()));
else
    return(op.getMethod().invoke(expr.getNext(), expr.getNext().getNext()));

但是,我仍然不完全喜欢这个解决方案,因为我正在失去类型安全性,而且它看起来仍然不是那么好。我在 stackoverflow 上看到的另一个例子看起来很优雅但我不完全理解是顶部答案的第一个解决方案:How to call a method stored in a HashMap? (Java)

Stackoverflow 上的每个人都认为最好的解决方案是什么?

编辑:以防万一有人搜索此内容并对我的解决方案感到疑惑,我让每个操作(例如 Add、Car、Cdr)都有自己的类来实现 Command。然后我不得不将我的大部分方法设为静态,我想它们中的每一个本质上都是静态的。这似乎比原来的 case 语句更优雅。

最佳答案

基本上,答案建议使用命令模式。

"The main advantage of the command design pattern is that it decouples the object that invokes the operation from the one that know how to perform it. And this advantage must be kept. There are implementations of this design pattern in which the invoker is aware of the concrete commands classes. This is wrong making the implementation more tightly coupled. The invoker should be aware only about the abstract command class"
  1. 基本上您的 map 是类型安全的。通过声明 Map <character,Command>
  2. 对可扩展性持开放态度

关于java - switch 语句或远程调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843722/

相关文章:

java - (错误)GlassFish : publishModule kind= 3 deltaKind=2 1 WebApp

c# - 激活器.CreateInstance : Could not load type from assembly

C# 反射 - 加载程序集并调用方法(如果存在)

尝试更改变量的 Java 方法不起作用

Java 方法 boolean 值在应该为 true 时返回 false

java - Spring Boot自动创建数据库表

java - 如何检查 OnClickListener 内的线程是否完成

c++ - 在 C++ 类方法中使用 *this 完全覆盖自实例化

java - 使用 envers 进行 Junit 测试

java - 设置作为另一个对象的子对象的对象的字段值