Search code examples
javaoverloadingmultiple-dispatchmethod-dispatchdynamic-dispatch

Work around Java's static method dispatching without Double Dispatch/Visitor patterns


I am using a class Foo that provides these methods:

String overloadedMethod(Object)
String overloadedMethod(Goo)

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.

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)
}

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


Solution

  • 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.

    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.