Metaprogramming
metaprogramming2MethodHandles
- Path
- pkg17metaprogramming/metaprogramming2MethodHandles.java
- Package
- pkg17metaprogramming
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg17metaprogramming/metaprogramming2MethodHandles.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg17metaprogramming;2 3import java.lang.invoke.MethodHandle;4import java.lang.invoke.MethodHandles;5import java.lang.invoke.MethodType;6 7/*8 * metaprogramming2MethodHandles.java9 * ------------------------------------10 * MethodHandles: faster, type-safe reflective invocation (Java 7+).11 *12 * DEFINITION:13 * MethodHandles (java.lang.invoke) are the low-level building blocks behind14 * lambdas and invokedynamic. They are more efficient than raw Reflection.15 *16 * KEY POINTS:17 * - Lookup.unreflect() or findVirtual/findStatic obtain a MethodHandle.18 * - invoke() / invokeExact() call the target with correct types.19 * - Used by the JVM for lambda generation and by libraries needing speed.20 */21public class metaprogramming2MethodHandles {22 23 static class Calculator {24 int add(int a, int b) { return a + b; }25 static int multiply(int a, int b) { return a * b; }26 }27 28 public static void main(String[] args) throws Throwable {29 Calculator calc = new Calculator();30 MethodHandles.Lookup lookup = MethodHandles.lookup();31 32 // Virtual method handle33 MethodHandle add = lookup.findVirtual(Calculator.class, "add",34 MethodType.methodType(int.class, int.class, int.class));35 int sum = (int) add.invoke(calc, 10, 32);36 System.out.println("add(10,32) via MethodHandle = " + sum);37 38 // Static method handle39 MethodHandle mul = lookup.findStatic(Calculator.class, "multiply",40 MethodType.methodType(int.class, int.class, int.class));41 int product = (int) mul.invoke(6, 7);42 System.out.println("multiply(6,7) via MethodHandle = " + product);43 44 // Bound handle (receiver fixed)45 MethodHandle boundAdd = add.bindTo(calc);46 System.out.println("bound add(1,2) = " + boundAdd.invoke(1, 2));47 }48}