Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What are Java Reflection and MethodHandles, and why is MethodHandles faster?
senior LevelCode ExampleSystem Design
In Simple Words:
- Reflection (
java.lang.reflect): Allows code to inspect classes, fields, and methods at runtime and invoke private members dynamically. However, it performs expensive access-permission checks on every single invocation and prevents JIT compiler inlining. MethodHandles(java.lang.invoke): Introduced in Java 7,MethodHandlesprovides typed, directly executable references to underlying methods.
Why MethodHandles Outperforms Classic Reflection:
- One-Time Access Check: Security and visibility permissions are checked once during lookup (
MethodHandles.Lookup), not on each execution. - JIT Inlining: The JVM treats a
MethodHandleas direct bytecode instructions (invokevirtual/invokespecial), allowing the JIT compiler to inline the call target just like ordinary direct method invocations.
java
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType type = MethodType.methodType(String.class, int.class);
MethodHandle handle = lookup.findVirtual(CustomerService.class, "getCustomerName", type);
CustomerService service = new CustomerService();
String name = (String) handle.invokeExact(service, 101);