在没有Double Dispatch / Visitor模式的情况下解决Java的静态方法调度问题 [英] Work around Java's static method dispatching without Double Dispatch/Visitor patterns

查看:167
本文介绍了在没有Double Dispatch / Visitor模式的情况下解决Java的静态方法调度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用提供这些方法的类 Foo

I am using a class Foo that provides these methods:

String overloadedMethod(Object)
String overloadedMethod(Goo)

由于Java静态调度非接收器参数,我不能只传递我的(这是一个对象,但可能有动态类型 Goo )并依赖JVM动态选择正确方法。

Since Java statically dispatches on the non-receiver argument, I cannot just pass my value (which is an Object, but might have dynamic type Goo) and rely on the JVM to dynamically choose the "correct" method.

这是我当前(丑陋)的工作-around:

This is my current (ugly) work-around:

Object value = ...;
Foo foo = new Foo();
if (value instanceof Goo) {
    Goo gooValue = (Goo) value;
    return foo.overloadedMethod(gooValue); // -> overloadedMethod(Goo)
} else {
    return foo.overloadedMethod(value);    // -> overloadedMethod(Object)
}

有没有更好的方法来做这个没有修改 Foo 中的代码(包含重载方法的类)?

Is there a better way of doing this without modifying the code in Foo (the class containing the overloaded method)?

推荐答案

当然你总是可以使用反射来找到适用的方法的最具体版本,但这可能很快就会变得毛茸茸。

Of course you could always use reflection to find the most specific version of the method that applies, but that could get hairy real quick.

但是如果这两个调用导致完全不同的行为,然后Foo被设计为在访问者模式中使用(即双重调度)或者它被破坏。

But if those two calls result in entirely different behaviour, then Foo is either designed to be used in a visitor pattern (i.e. with double dispatch) or it is broken.

这篇关于在没有Double Dispatch / Visitor模式的情况下解决Java的静态方法调度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆