12. Sample code snippet import java.lang.invoke.*; import java.sql.*; public class Query { static { //Bootstrap method Linkage.registerBootstrapMethod("doBootstrap"); } public static ResultSet query(String queryString, Object... params) { //Performs query, return ResultSet } public static CallSite doBootstrap(Class caller, String methodName, MethodType type) { MethodHandles.Lookup lookup = MethodHandles.lookup(); //Lookup the class that has the method that we will be linking to //In this case, query is in the same class Class me = lookup.lookupClass(); //Lookup query method by matching the parameter type and return type MethodHandle rawQuery = lookup.findStatic(me, "query" , MethodType.methodType(ResultSet.class, String.class, Object[].class)); //Set the method name as the first parameter to query() MethodHandle cookedQuery = MethodHandles.insertArguments(rawQuery, 0, methodName); //Return a CallSite object back to the JVM to continue with the call return (new ConstantCallSite(MethodHandles.collectArguments(cookedQuery, type))); }
13. public static void main(String... args) throws Throwable { //Invoking this will result in doBootstrap() method being called ResultSet result = InvokeDynamic.<ResultSet>findByTitleAndAuthor ("The Shining", "Stephen King"); String val = InvokeDynamic.<String>findByTitleAndAuthor ("Lord of the Rings", "JRR Tolkein"); } } //java -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic Query