Java – Use MethodHandles and invokedynamic linked method calls

Use MethodHandles and invokedynamic linked method calls… here is a solution to the problem.

Use MethodHandles and invokedynamic linked method calls

Think of dynamic, predictive aspect language. Aspects (that is, methods) can be called in place of or before and after the original methods. These aspects are turned on and off at runtime. It may even be that multiple parties want to change the same method, which will cause these aspects to be combined into a single method call chain.

The original method is changed by the compiler (JPLIS and ASM) at load time. I got some bytecode that looks like this :

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

Interestingly, the bootstrapping method should work in a specific way:

  • Returns a concatenation of methods with a list of compatible parameters. These MethodHandle bindings (bind) to different instances of the different types that call them.
  • A possible MethodHandle is simply bound to other instances, not to the instance that calls the Bootstrap method. Therefore, the use of this call result call point (the first branch in the alternative below) should be omitted.

It is also possible to call the original method directly, which is completely fine.

enter image description here

In my opinion, MethodHandle is the right way to achieve this.
My question is whether everything can be implemented in a single bootstrap method so that I can chain the method call, as shown in the sequence diagram, using the method handle chain returned from the binding (bind) to the bootstrap method call point.

Solution

Any branching logic that decides which aspects to apply to a method call must run when the method handle executes, not at bootstrap time.

You can < a by
combining various handles and branching logic href=” http://download.java.net/java/jdk9/docs/api/java/lang/invoke/MethodHandles.html#guardWithTest-java.lang.invoke.MethodHandle-java.lang.invoke.MethodHandle-java.lang.invoke.MethodHandle- ” rel=”noreferrer noopener nofollow”>MethodHandles.guardWithTest​(test, target, fallback)

This on the stack becomes one of the parameters of the handle.

Related Problems and Solutions