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)?
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.
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)
来源:https://stackoverflow.com/questions/370812/work-around-javas-static-method-dispatching-without-double-dispatch-visitor-pat