lschuetze
lschuetze

Reputation: 1218

Chain method calls using MethodHandles and invokedynamic

Think of a dynamic, predicated aspect language. Aspects could be invoked (i.e., methods) instead of or before and after an original method. These aspects are switched on and off which happens at runtime. It could even be, that multiple aspects want to change the same method, which will result in a composition of these aspects into a chain of method calls.

The original method is changed by a loadtime compiler (JPLIS and ASM). I got some bytecode looking something like this:

//## baseMethod ##
aload 0         // this
aload ...       // some more arguments
invokedynamic # // call the bootstrap method which returns a callsite to be invoked

The interesting part is that the bootstrap method should work in a specific way:

It may also happen that the original method is directly called, which is totally okay.

enter image description here

It seems to me that MethodHandles are the right thing to achieve this. My question would be if everything is achievable in a single bootstrap method as such that I can chain the method calls as shown in the sequence diagram using a chain of method handles returned from the bootstrap method that are bound to the callsite.

Upvotes: 3

Views: 594

Answers (1)

the8472
the8472

Reputation: 43117

Any branching logic that will decide which aspects to apply to a method invocation have to run at method handle execution time, not at bootstrap time.

You can combine the various handles and the branching logic via
MethodHandles.guardWithTest​(test, target, fallback)

The this on the stack will be one of the arguments for the handles.

Upvotes: 3

Related Questions