skip to content

Reflection, MethodHandles & VarHandle

Runtime introspection and dynamic invocation: the Class object, member access, setAccessible under the module system, annotations and generics via reflection, dynamic proxies, MethodHandles and VarHandle. This is the machinery every Java framework runs on, which is why interviewers ask.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

What is MethodHandles.privateLookupIn and when would you use it for cross-class or cross-module access?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

privateLookupIn lets one class obtain a Lookup with private-level access into another class, so it can build handles for that class's private members. The caller must already be allowed to reach the target (same module, or the target's module has opened the package), making it the module-aware replacement for setAccessible.

open as a page

As a library author whose framework injects into consumers' private fields, how do you handle Java's strong encapsulation without forcing every user to add --add-opens?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

Ask consumers to 'opens' their own packages to your framework (ideally a qualified open) in their module-info, probe with trySetAccessible and fail with a clear message if access is missing, and offer non-reflective paths (constructor/setter injection or MethodHandles) so --add-opens flags aren't mandatory.

open as a page

When would you choose MethodHandles or VarHandle over the classic reflection API for dynamic invocation and field access?

level: principalimportance: nice to knowfreq 35%

basics

~20 s

Use classic reflection (Method/Field/Constructor) for occasional, flexible introspection like config parsing or scanning annotations. Use MethodHandles and VarHandle when you call/access repeatedly on a hot path and need speed, because they're strongly typed, JIT-inlinable, and (VarHandle) give controlled memory ordering for fields.

open as a page

What are the risks and modern constraints of using reflective member introspection plus setAccessible to reach non-public members?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

Reflecting into private members breaks encapsulation: you couple to internals that can change and lose compile-time safety. Modern Java's module system also blocks setAccessible on packages that aren't opened, so it can fail at runtime.

open as a page

showing 31–34 of 34