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

2

3

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

Hydrophilous answered 16/12, 2008 at 9:41 Comment(0)
P
3

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.

Prochora answered 16/12, 2008 at 9:43 Comment(0)
C
2

You could take a look at the Java MultiMethod Framework. It's pretty much a layer around what you're proposing, but atleast it's abstracted into a logical module that's not your responsibility?

(As far as I'm aware, there's no clean way to do this without resorting to reflection/instanceof hacking)

Chancery answered 16/12, 2008 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.