Skip to main content
InterviewHubPRO
Section Overview
Q18

Question 18 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

36%
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, MethodHandles provides typed, directly executable references to underlying methods.

Why MethodHandles Outperforms Classic Reflection:

  1. One-Time Access Check: Security and visibility permissions are checked once during lookup (MethodHandles.Lookup), not on each execution.
  2. JIT Inlining: The JVM treats a MethodHandle as 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);