Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package ravi.tutorial.java.java7; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; public class MethodHandleTest { public static void main(String[] args) throws Throwable { /* * Prepare lookup */ MethodHandles.Lookup lookup = MethodHandles.lookup(); /* * Create a method type which has signature as * * Return type = Double, First method argument = Integer, Second method argument * = Long * * This is for matching add method in Calculator class */ MethodType mt = MethodType.methodType(Double.class, Integer.class, Long.class); /* * Get method handle from class Calculator, with method name 'add' and matches * method signature as per mt method type. */ MethodHandle mh = lookup.findVirtual(Calculator.class, "add", mt); /* * Call method on calcObject with method arguments as arg_1 & arg_2 */ Calculator calcObject = new Calculator(); Integer arg_1 = 1; Long arg_2 = 2l; Double output = (Double) mh.invokeExact(calcObject, arg_1, arg_2); System.out.println(output); } } /* * Demo class */ class Calculator { public Double add(Integer a, Long b) { Long l = (a + b); return l.doubleValue(); } } |
Output:
1 |
3.0 |