Use invokedynamic to implement multiple dispatch
Asked Answered
H

2

9

I wondered if Java7's new invokedynamic bytecode instruction could be used to implement multiple dispatch for the Java language. Would the new API under java.lang.invoke be helpful to perform such a thing?

The scenario I was thinking about looked as follows. (This looks like an application case for the visitor design pattern, but there may be reasons that this is not a viable option.)

class A {} 
class A1 extends A {}
class A2 extends A {}

class SomeHandler {
    private void doHandle(A1 a1) { ... }
    private void doHandle(A2 a2) { ... }
    private void doHandle(A a) { ... }

    public void handle(A a) {
        MultipleDispatch.call(this, "doHandle", a);
    }
}

The library class MultipleDispatch would then do something of the kind:

class MultipleDispatch {

    public static Object call(Object receiver, String method, Object...arg) {
        // something like that in byte code
        #invokeDynamic "doHandle" "someBootstrap"
    }

    static CallSite someBootstrap {
        // resolve that dynamic method call.
    }
}

(I am aware of MultiJava, but can this be achieved in a Java-pure fashion?)

Have answered 13/6, 2012 at 12:34 Comment(4)
It may be worth looking at MethodHandles in Java 7 as these can use dynamic dispatch.English
Nice question (+1). Is there a word missing in your 1st sentence (freshly added what, CallSite?)?Healing
Weird that this question got so little attention :(Healing
should I start a bounty?Healing
H
2

Since I have no experience with invokedynamic, I do not know how good the performance and type-safety would be, but can only give some pointers:

Healing answered 17/6, 2012 at 9:19 Comment(0)
I
1

The instruction invokedynamic is purely a JVM instruction, it does not relate to dynamic dispatch. The dispatch is completed by method handles (method handle graph and method handle tree are also OK.) that comprises multiple method handle instances. A path in the graph (tree) represents one dispatch path.

For your given sample, i would possible construct a graph (Different people might have different graph result ). IN this graph, the traverse of method handles in the graph is the way how disptach completes.

sample method handle tree

Isolate answered 12/11, 2014 at 3:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.