views:

877

answers:

2

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

+3  A: 

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.

Joachim Sauer
+2  A: 

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)

Martin