Skip to content
Tutorials Center
My learning

Topics

Lesson 155 of 201 ยท JVM and Advanced Topics

Reflection

Learn Java reflection - Class objects, inspecting and changing fields, invoking methods, creating instances, setAccessible and modules, proxies and method handles.

Normally your code knows the types it works with when you write it: you call book.title() because you know book is a Book. Reflection lets a program work with types it has never seen. Given any object, it can ask "what class are you, what fields and methods do you have?", read and change those fields, call those methods, and create new instances, all by name and at run time.

That sounds exotic, but you rely on it every day. JUnit finds your @Test methods with reflection. Jackson turns any object into JSON by reading its fields or accessors. Spring creates your services and passes them their dependencies. Hibernate fills entity fields from database rows. In the previous lesson you used reflection to read annotations; this lesson covers the whole java.lang.reflect toolbox, its limits under the module system, dynamic proxies and method handles, and when you should (and shouldn't) use it yourself.

The Class object

Every type in a running JVM is represented by one java.lang.Class object. There are three ways to get it:

Java
Class<String> a = String.class;                        // class literal: known at compile time
Class<?> b = "hello".getClass();                       // from an object: its runtime class
Class<?> c = Class.forName("java.time.LocalDate");     // by fully qualified name: may throw ClassNotFoundException

Class.forName is the truly dynamic one: the name can come from a configuration file, which is how JDBC drivers and plugins were traditionally loaded. Nested classes use a $ in their binary name, like Main$Book. Primitives and arrays have Class objects too: int.class, int[].class, String[][].class.

Java Asking a Class about itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few details worth noticing: an interface's superclass is null, records always extend java.lang.Record and are final, our classes live in the unnamed package (an empty package name), and nested types show static because nested records and interfaces are implicitly static. Arrays and primitives are special: getName() uses a JVM descriptor for arrays ([I means "array of int"), both report the package java.lang, and their modifiers include abstract final because you can't instantiate them with a constructor or extend them. Arrays and primitives are special: their getName() uses JVM descriptors ([I means "array of int"), they report the package java.lang, and their modifiers always include abstract final because you can neither instantiate nor subclass them with new/extends.

Class is generic: String.class has type Class<String>, so methods like cast and getDeclaredConstructor().newInstance() return the right type without a cast. When the type isn't known, you work with Class<?>.

Inspecting fields, methods and constructors

Class has two families of member lookups:

Methods Returns
getFields(), getMethods(), getConstructors() Public members only, including inherited ones (for fields and methods)
getDeclaredFields(), getDeclaredMethods(), getDeclaredConstructors() All members declared in this class (any access level), no inherited ones
getField(name), getMethod(name, paramTypes...), ... One specific member, same rules; throws NoSuchFieldException / NoSuchMethodException

Methods are identified by name and parameter types, because of overloading: getMethod("add", int.class, int.class). The order of the arrays returned by getDeclared... is unspecified, so sort them if order matters. Each member object tells you its name, type, modifiers, annotations and, for generic declarations, the full generic type via getGenericType() or getGenericReturnType().

Java Printing an outline of a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The filter on isSynthetic() and isBridge() hides methods the compiler generated behind the scenes. Implementing Comparable<SavingsAccount> makes javac add a bridge method compareTo(Object) that casts and calls your compareTo(SavingsAccount), a side effect of type erasure. Remove the filter to see it.

Parameter names are usually not available: Parameter.getName() returns arg0, arg1 unless the code was compiled with javac -parameters. Spring Boot's build plugins turn that flag on for you.

Reading and writing fields

A Field can get and set the value of that field on any instance (or with null as the instance for a static field). Private members are off-limits by default; setAccessible(true) switches off the access check for that one reflective object:

Java A reflective toString and changing a private field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

setAccessible(true) works here because Product is in the same module as the caller. Notice what just happened, though: code outside the class changed a private field, bypassing every check the class might have had. That's exactly why the module system restricts it (more on that below), and why you should treat reflective writes as a framework tool, not an everyday technique.

There are typed accessors (getInt, setDouble, ...) to avoid boxing, and you can't change a static final field at all. Non-static final fields of ordinary classes can still be changed after setAccessible(true), but the JIT may have already inlined the old value, so the result is unreliable; record fields and hidden classes refuse with IllegalAccessException. Newer JDKs are moving to forbid final-field mutation entirely, so never depend on it.

Invoking methods

Method.invoke(target, args...) calls a method. Pass null as the target for static methods. Two things surprise people:

  1. Arguments and results are boxed. invoke takes Object... and returns Object, so an int result comes back as an Integer, and a void method returns null.
  2. Exceptions are wrapped. If the called method throws, invoke throws InvocationTargetException; the real exception is getCause(). Forgetting to unwrap it makes logs say "InvocationTargetException" with no useful message.
Java Calling methods by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Creating instances

To create an object reflectively, get a Constructor and call newInstance:

Java
Calculator c = Calculator.class.getDeclaredConstructor().newInstance();       // no-arg constructor
Book b = Book.class.getDeclaredConstructor(String.class, int.class).newInstance("Dune", 1965);
int[] numbers = (int[]) java.lang.reflect.Array.newInstance(int.class, 5);  // arrays

The old Class.newInstance() is deprecated because it rethrows the constructor's checked exceptions without declaring them. For a record, the canonical constructor's parameter types are the component types, in order.

This is enough to build the core of a dependency injection container. The container looks at a class's constructor, creates each parameter's type first (recursively), and passes the results in, so no class has to create its own dependencies:

Java A tiny dependency injection container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Spring's container does the same thing with far more features: interfaces mapped to implementations, scopes, cycle detection, configuration and proxies. You'll see the real thing in the Advanced Java track.

setAccessible and the module system

Before Java 9, setAccessible(true) could open anything, including the JDK's own internals. Libraries depended on that, and every JDK upgrade risked breaking them. Since Java 16 the JDK's internals are strongly encapsulated: a module must explicitly open a package before other modules can use deep reflection on its private members. java.base doesn't open java.lang, so:

Java Strong encapsulation stops deep reflection into the JDK

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You can find the private field (metadata is visible), but making it accessible throws InaccessibleObjectException. trySetAccessible() returns false instead of throwing, which is handy for libraries with a fallback. The escape hatch is a command-line flag, --add-opens java.base/java.lang=ALL-UNNAMED, which you'll still see in some build files for older libraries. In your own modular applications, the module system lesson shows how opens grants this access deliberately, for example to let Hibernate or Jackson read your entity fields.

Dynamic proxies

java.lang.reflect.Proxy creates, at run time, an object that implements any interfaces you choose. Every method call on it goes to a single InvocationHandler, which can log, time, check permissions, cache, or forward the call to a real object. This is how Spring adds @Transactional behavior, how mocking libraries work, and how many RPC clients turn interface calls into network requests.

Java A timing and logging proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

JDK proxies only work with interfaces. Frameworks that proxy classes (Spring with CGLIB or ByteBuddy, Hibernate's lazy-loading proxies) generate subclasses with bytecode libraries instead. The Structural and Behavioral Patterns lesson shows the Proxy pattern written by hand.

Method handles

java.lang.invoke.MethodHandle (Java 7) is a lower-level, faster alternative to Method. You look up a handle once with a MethodHandles.Lookup, which checks access at lookup time using the caller's permissions, and then call it with invoke or the strictly typed invokeExact. The JIT can inline method handle calls stored in static final fields almost like direct calls.

Java
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle length = lookup.findVirtual(String.class, "length", MethodType.methodType(int.class));
MethodHandle max = lookup.findStatic(Math.class, "max", MethodType.methodType(int.class, int.class, int.class));

int n = (int) length.invokeExact("reflection");   // 10
int m = (int) max.invoke(3, 9);                   // 9

VarHandle (Java 9) is the field equivalent, with atomic operations like compareAndSet; the atomic variables in java.util.concurrent are built on it. Lambdas, string concatenation and records' toString all run on method handles under the hood. Here is the same lookup in a runnable program, compared with plain reflection:

Java Method handles vs reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

invokeExact requires the call site's types to match the handle's type exactly, including the cast on the result, which is why (String) appears before each call. Assigning the result to Object fails at run time. Use invoke when you want automatic conversions.

When to use reflection (and when not)

Reflection is the right tool when you write generic infrastructure that must work with classes it can't know in advance: serializers, test runners, dependency injection, ORMs, plugin loaders, command routers, debugging tools. In application code, it's almost always the wrong tool. Its costs:

  • No compile-time safety. A typo in "getPrice" or a renamed method compiles fine and fails at run time. Refactoring tools can't see string-based references.
  • Broken encapsulation. Writing private fields bypasses validation and invariants (see Encapsulation).
  • Speed. Each reflective call checks access and boxes arguments. Modern JDKs implement Method.invoke with method handles, so it's much faster than it used to be, but still slower than a direct call. Look members up once and cache them.
  • Ahead-of-time compilation. GraalVM Native Image must know at build time which classes are reflected on, so reflection-heavy code needs extra configuration.

If an interface, a lambda, a switch over a sealed type or a Map<String, Function<...>> solves the problem, prefer it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Class Dog extends Animal. Animal has a public method eat(); Dog declares a private method bark(). Which call finds both?

    getMethods returns public methods including inherited ones (eat but not the private bark); getDeclaredMethods returns all methods declared in Dog (bark but not the inherited eat).
  2. 2. A method called through Method.invoke throws IllegalStateException. What does the caller of invoke catch?

    invoke wraps any exception thrown by the target method in InvocationTargetException. Unwrap it with getCause().
  3. 3. What does String.class.getDeclaredField("value").setAccessible(true) do in code on the class path in Java 25?

    The field exists and can be found, but strong encapsulation forbids deep reflection into packages a module hasn't opened. Only --add-opens would allow it.
  4. 4. What can a JDK dynamic proxy created with Proxy.newProxyInstance implement?

    JDK proxies implement the interfaces you pass in, and every call goes to the InvocationHandler. Proxying classes requires bytecode libraries like ByteBuddy.
  5. 5. Method m = type.getMethod("size"); returns an int-returning method. What is the static type and runtime class of m.invoke(list)?

    invoke is declared to return Object, and primitive results are boxed, so you get an Integer that you must cast or unbox.

Summary

  • Every type has one Class object: get it with X.class, obj.getClass() or Class.forName("pkg.Name").
  • getFields/getMethods/getConstructors return public members (fields and methods include inherited ones); getDeclared... return all members of that class only.
  • Field.get/set, Method.invoke and Constructor.newInstance work by name at run time; values are boxed, and invoke wraps thrown exceptions in InvocationTargetException.
  • setAccessible(true) reaches private members in your own code, but the module system blocks deep reflection into packages that aren't opened (InaccessibleObjectException).
  • Proxy builds interface implementations at run time that route every call through one handler; method handles are a faster, access-checked-once alternative to Method.
  • Reflection powers frameworks (DI, serialization, testing, ORMs). In application code, prefer interfaces and lambdas, and cache reflective lookups when you do use it.

Next: The Java Module System (JPMS), where you'll declare modules with module-info.java and decide exactly what other code may see and reflect on.