|
| 1 | +package com.brianway.learning.java.jvm.dynamictype; |
| 2 | + |
| 3 | +import static java.lang.invoke.MethodHandles.lookup; |
| 4 | + |
| 5 | +import java.lang.invoke.CallSite; |
| 6 | +import java.lang.invoke.ConstantCallSite; |
| 7 | +import java.lang.invoke.MethodHandle; |
| 8 | +import java.lang.invoke.MethodHandles; |
| 9 | +import java.lang.invoke.MethodType; |
| 10 | + |
| 11 | +/** |
| 12 | + * Created by brian on 17/3/20. |
| 13 | + * invokedynamic 指令演示 |
| 14 | + */ |
| 15 | +public class InvokeDynamicTest { |
| 16 | + |
| 17 | + public static void main(String[] args) throws Throwable { |
| 18 | + INDY_BootstrapMethod().invokeExact("brianway"); |
| 19 | + } |
| 20 | + |
| 21 | + public static void testMethod(String s) { |
| 22 | + System.out.println("hello String:" + s); |
| 23 | + } |
| 24 | + |
| 25 | + public static CallSite BootstrapMethod( |
| 26 | + MethodHandles.Lookup lookup, String name, MethodType mt) |
| 27 | + throws Throwable { |
| 28 | + return new ConstantCallSite(lookup.findStatic(InvokeDynamicTest.class, name, mt)); |
| 29 | + } |
| 30 | + |
| 31 | + private static MethodType MT_BootstrapMethod() { |
| 32 | + return MethodType.fromMethodDescriptorString( |
| 33 | + "(Ljava/lang/invoke/MethodHandles$Lookup;" + |
| 34 | + "Ljava/lang/String;Ljava/lang/invoke/MethodType;)" + |
| 35 | + "Ljava/lang/invoke/CallSite;", null |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + private static MethodHandle MH_BootstrapMethod() throws Throwable { |
| 40 | + return lookup().findStatic(InvokeDynamicTest.class, "BootstrapMethod", |
| 41 | + MT_BootstrapMethod()); |
| 42 | + } |
| 43 | + |
| 44 | + private static MethodHandle INDY_BootstrapMethod() throws Throwable { |
| 45 | + CallSite cs = (CallSite) MH_BootstrapMethod().invokeWithArguments( |
| 46 | + lookup(), |
| 47 | + "testMethod", |
| 48 | + MethodType.fromMethodDescriptorString( |
| 49 | + "(Ljava/lang/String;)V", null |
| 50 | + )); |
| 51 | + return cs.dynamicInvoker(); |
| 52 | + } |
| 53 | +} |
0 commit comments