java / expert
Snippet
Dynamic Invocation with MethodHandles
MethodHandles are the core mechanism behind 'invokedynamic'. They provide a more performant and type-safe alternative to traditional Reflection. Once a MethodHandle is linked, the JVM can optimize the call similarly to a direct method invocation.
snippet.java
1
2
3
MethodType mt = MethodType.methodType(String.class, char.class, char.class);MethodHandle mh = MethodHandles.lookup().findVirtual(String.class, "replace", mt);String result = (String) mh.invokeExact("hello", 'e', 'a');
Breakdown
1
MethodType.methodType(...)
Defines the signature (return type and parameter types) for the method search.
2
findVirtual(String.class, "replace", mt)
Looks up the virtual method 'replace' in the String class matching the signature.
3
mh.invokeExact(...)
Invokes the handle; 'exact' requires the arguments to match the signature perfectly.