Reflection and access
What you will learn
Reflection represents types and members as Java objects. Use it when code must inspect a known type at runtime; prefer direct calls when the target is already known. Finding a member does not grant permission to access it.
- Distinguish public and declared member lookup.
- Inspect a public field and its generic declaration.
- Invoke a reviewed public method and interpret lookup, access and target failures.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Compile with -proc:none to disable annotation processors. Run only these reviewed examples in a fresh lab-owned directory. Service fixtures create and clean up fixed local registration resources. No external plugins or private access bypass.
Find an inherited public method
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public static class Parent { public String name() { return "report"; } } public static class Report extends Parent { public int pages = 3; private int secret = 7; public String format(int count) { return "pages=" + count; } public void reject() { throw new IllegalStateException("invalid"); } public List<String> tags = List.of("daily"); } public static void main(String[] args) throws Throwable { Method m = Report.class.getMethod("name"); System.out.println(m.getDeclaringClass().getSimpleName()); System.out.println(m.invoke(new Report())); System.out.println(Report.class.getDeclaredMethod("format", int.class).getReturnType().getSimpleName()); }}Expected output:
ParentreportStringPublic lookup sees the inherited method; declared lookup finds format on Report.
Class, Method and Field
A class literal such as Report.class yields a Class object; object.getClass() identifies its actual runtime class. getMethod searches public members including inherited ones; getDeclaredMethod selects a member declared by that type, including non-public ones. Supply exact formal parameter classes, such as int.class, not Integer.class. getField and getDeclaredField make the analogous public/declared distinction. Do not depend on reflection array order; sort explicitly. Field.getType returns the erased class, while getGenericType can reveal declared type arguments; this does not restore actual runtime collection element types.
Invocation and access
Method.invoke takes a receiver (null for static methods) and arguments, returns Object with boxed primitive results or null for void. Wrong arguments can throw IllegalArgumentException; absent members cause NoSuchMethodException or NoSuchFieldException; denied access produces IllegalAccessException. An exception thrown by the invoked method is wrapped in InvocationTargetException. Handle the cause deliberately without swallowing errors. Reflecting private members does not make them public or supported. Java Platform Module System (JPMS) exports govern public access and opens govern deep reflection. This chapter never suppresses access checks, opens modules or invokes private members.
Method handles
A MethodHandle is a typed callable reference. A Lookup checks access when resolving a handle; MethodType describes the parameter and return types. findVirtual looks up a virtual method using its declared signature; the returned handle includes the receiver as its first argument. invokeExact requires an exact call-site type, including the return type. The examples use publicLookup on a reviewed public class and declare throws Throwable because the handle can propagate the target failure. Direct calls remain simpler for ordinary application code.
Inspect a field and its generic type
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public static class Parent { public String name() { return "report"; } } public static class Report extends Parent { public int pages = 3; private int secret = 7; public String format(int count) { return "pages=" + count; } public void reject() { throw new IllegalStateException("invalid"); } public List<String> tags = List.of("daily"); } public static void main(String[] args) throws Throwable { Field f = Report.class.getField("tags"); System.out.println(f.getType().getSimpleName()); System.out.println(f.getGenericType().getTypeName()); System.out.println(Report.class.getField("pages").get(new Report())); System.out.println(Modifier.isPrivate(Report.class.getDeclaredField("secret").getModifiers())); }}Expected output:
Listjava.util.List<java.lang.String>3trueGeneric metadata describes the declaration. Inspecting private modifiers is not reading the private value.
Invoke and distinguish target failure
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public static class Parent { public String name() { return "report"; } } public static class Report extends Parent { public int pages = 3; private int secret = 7; public String format(int count) { return "pages=" + count; } public void reject() { throw new IllegalStateException("invalid"); } public List<String> tags = List.of("daily"); } public static void main(String[] args) throws Throwable { Report report = new Report(); System.out.println(Report.class.getMethod("format", int.class).invoke(report, 2)); try { Report.class.getMethod("reject").invoke(report); } catch (InvocationTargetException e) { System.out.println(e.getCause().getClass().getSimpleName()); } }}Expected output:
pages=2IllegalStateExceptionLookup and invocation are separate operations; the target failure is wrapped.
Call a typed public method handle
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public static class Parent { public String name() { return "report"; } } public static class Report extends Parent { public int pages = 3; private int secret = 7; public String format(int count) { return "pages=" + count; } public void reject() { throw new IllegalStateException("invalid"); } public List<String> tags = List.of("daily"); } public static void main(String[] args) throws Throwable { MethodHandle handle = MethodHandles.publicLookup().findVirtual(Report.class, "format", MethodType.methodType(String.class, int.class)); String text = (String) handle.invokeExact(new Report(), 4); System.out.println(text); }}Expected output:
pages=4The handle call has the exact receiver, argument and return types.
Common mistakes
Do not use reflection as a replacement for direct method calls, guess overloads from runtime arguments, rely on array order, or bypass private access. Do not mistake List<String> declaration metadata for proof that every actual element is a String.
Practice
Look up the public format method with int.class, call it on a Report with argument 5 and print the result. Explain why Integer.class would not find the method.
Expected output:
pages=5Compare your answer with the manual practice criteria.
Official reading: Class · Method · Field · AccessibleObject · MethodHandles.Lookup · MethodHandle. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and access — knowledge check
Original metadata, reflection and service discovery questions. Java 21-compatible scope.
Which lookup includes inherited public methods?
Which type identifies an int formal parameter?
What wraps a target exception from Method.invoke?
What does getGenericType describe?
When does a Lookup check member access?