Reflection in Java Tutorial: Inspect Classes and Invoke Methods at Runtime

Learn Java Reflection from its Class<?> entry point to runtime construction, field access and method invocation. Trace one complete program and diagnose its common failures.

KnowledgeGate Team

Exam prep & CS education

Updated 15 Nov 20266 min read
Reflection in Java Tutorial: Inspect Classes and Invoke Methods at Runtime

You know how to write account.addBonus(25), but how does a framework create an object, read annotations or call a method when that method name does not appear in an ordinary call? Reflection lets a running Java program inspect and operate on runtime class metadata. The BankAccount trace constructs private state, changes its balance through Field, invokes addBonus through Method, and ends at exactly 1500. It also exposes access and exception traps. When the target is already known, however, a direct call remains clearer.

What Reflection is and what Java exposes at runtime

Every loaded Java type has a Class<?> object. It describes constructors, fields, methods, modifiers, annotations, interfaces and related metadata. Constructor<?>, Field and Method represent particular members. They can also create an instance, read or change a field, or invoke a method.

Oracle's java.lang.reflect API documentation defines this package for reflective access while documenting encapsulation and access restrictions. Reflection is not source-code parsing, and finding a private API does not make that API stable.

The compile-time and runtime choices differ:

  • Direct: the compiler sees account.addBonus(25).

  • Reflective: the program receives "addBonus", asks BankAccount.class for a method with parameter type int.class, then invokes it with 25.

Both reach the same logic. Only lookup and invocation are dynamic. This is useful for dependency-injection containers, test tools, serializers, runtime annotation readers, plug-in loaders and debuggers. It is not a reason to replace a simple direct call.

Obtain a Class object and choose the right lookup API

Use BankAccount.class when the type is known in code, account.getClass() when an object already exists, and Class.forName("demo.BankAccount") when configuration supplies a fully qualified binary name. With a type known at compile time, BankAccount.class avoids name-based loading.

Need

Lookup

Private BankAccount(String, int)

getDeclaredConstructor(String.class, int.class)

Private balance

getDeclaredField("balance")

Private addBonus(int)

getDeclaredMethod("addBonus", int.class)

Inherited public toString()

getMethod("toString")

getConstructor and getMethod search public members, including applicable inherited public methods. The declared variants search members declared in that class, including private members, but do not search a superclass for its private declarations.

Parameter types must match exactly. Primitive int is represented by int.class, not Integer.class. Thus getDeclaredMethod("addBonus", Integer.class) throws NoSuchMethodException, even though the value 25 is boxed while travelling through Method.invoke.

Diagram comparing public lookups such as getMethod("toString") with declared lookups for BankAccount private members.

Worked example: construct, read, change and invoke

Save this complete program as ReflectionDemo.java:

java
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class BankAccount {
    private final String owner;
    private int balance;

    private BankAccount(String owner, int openingBalance) {
        this.owner = owner;
        this.balance = openingBalance;
    }

    private int addBonus(int percent) {
        if (percent < 0) {
            throw new IllegalArgumentException("percent must be >= 0");
        }
        int bonus = balance * percent / 100;
        balance += bonus;
        return bonus;
    }
}

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        Class<?> type = BankAccount.class;

        Constructor<?> constructor =
                type.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        Object account = constructor.newInstance("Asha", 1000);

        Field owner = type.getDeclaredField("owner");
        owner.setAccessible(true);

        Field balance = type.getDeclaredField("balance");
        balance.setAccessible(true);

        System.out.println("class=" + type.getSimpleName());
        System.out.println("owner=" + owner.get(account));
        System.out.println("opening=" + balance.getInt(account));

        balance.setInt(account, 1200);
        System.out.println("after-set=" + balance.getInt(account));

        Method addBonus = type.getDeclaredMethod("addBonus", int.class);
        addBonus.setAccessible(true);
        int bonus = (int) addBonus.invoke(account, 25);

        System.out.println("bonus=" + bonus);
        System.out.println("final-balance=" + balance.getInt(account));

        try {
            addBonus.invoke(account, -5);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            System.out.println(cause.getClass().getSimpleName()
                    + ": " + cause.getMessage());
        }
    }
}

Run it with:

Code
javac ReflectionDemo.java
java ReflectionDemo

The exact output is:

Code
class=BankAccount
owner=Asha
opening=1000
after-set=1200
bonus=300
final-balance=1500
IllegalArgumentException: percent must be >= 0

Trace it in five moves:

  1. Acquire the Class<?> metadata entry point.

  2. Look up the constructor by its exact String, int signature.

  3. Create an Object whose opening balance is 1000.

  4. Use getInt and setInt to read the primitive field and change it to 1200.

  5. Find addBonus(int) and invoke it. Method.invoke returns Object, so (int) unboxes the returned Integer.

The arithmetic is 1200 * 25 / 100 = 300; then 1200 + 300 = 1500. The method returns 300 and also mutates the same object's balance. The rejected -5 call throws before changing that state.

Diagram tracing the BankAccount run: balance starts at 1000, setInt raises it to 1200, and addBonus(25) returns 300 for 1500.

Access checks, encapsulation and modules

The constructor, fields and method are private, so ordinary reflective access fails until the demo suppresses access checking. setAccessible(true) works here because this is our class in a classpath-style unnamed module. It does not grant universal access to private members.

Use the decision-shaped alternative when denial must be handled explicitly:

java
if (!balance.trySetAccessible()) {
    throw new IllegalStateException("balance is not open for reflection");
}

Strongly encapsulated modules can reject suppressed access with InaccessibleObjectException in the cases described by Oracle's API contract. Prefer a public API, explicit factory, interface or configuration contract before depending on private reflection. Do not treat broad --add-opens flags as a routine fix, especially for private JDK internals.

Common Reflection errors and how to diagnose them

Symptom

Cause in this example

Fix

ClassNotFoundException

Wrong binary name in Class.forName

Check the full package and class name

NoSuchFieldException

"Balance" instead of case-sensitive "balance"

Use the declared spelling

NoSuchMethodException

Integer.class instead of int.class

Match the exact parameter token

IllegalAccessException

Private member found, access not enabled

Check trySetAccessible() or redesign access

IllegalArgumentException

Receiver or argument type does not match

Check receiver and signature

InvocationTargetException

addBonus(-5) ran and its target code threw

Inspect e.getCause()

InvocationTargetException is a wrapper, not the business error. The catch prints its cause, IllegalArgumentException: percent must be >= 0. Reporting only the wrapper hides the actionable failure.

Also remember that getDeclaredFields() order is not promised, so sort by Field.getName() for stable output. A subclass's getDeclaredField does not find a superclass's private field, so walk the superclass chain deliberately if your contract requires it. Repeated lookup also adds work, which is why frameworks validate and cache metadata instead of searching inside a hot loop.

Reflecting the String owner field does not change how strings behave. Review Java String Handling: String Pool and Immutability, and do not try to mutate String internals.

How interviews and objective questions test Reflection

Common question forms ask you to obtain Class, distinguish getMethod from getDeclaredMethod, match primitive parameter types, trace newInstance, getInt or invoke, and classify lookup, access and target exceptions. Syllabus coverage varies, so check your exam board's or target employer's own current material before you prioritise this topic.

Use a four-step trace: write runtime class BankAccount; write exact signature addBonus(int); check access; then separate returned value 300 from mutated state 1500. Replacing int.class with Integer.class fails during lookup, before the method runs.

KnowledgeGate currently offers 250+ live practice questions in Programming Languages > Java. Those questions span the whole language rather than Reflection alone, so treat them as broad Java practice around this topic.

Exercises, the short version and the next step

Try these checkable changes:

  1. Add private int limit = 2000, find it with getDeclaredField("limit"), set it to 2400, and print limit=2400.

  2. Request getDeclaredMethod("addBonus", Integer.class), predict NoSuchMethodException, then fix it with int.class.

  3. Change -5 to -10. The cause remains IllegalArgumentException with the same message, and balance remains 1500.

  4. Stream type.getDeclaredFields(), map Field::getName, sort, and expect balance then owner.

For a design exercise, define interface AccountAction { int apply(BankAccount account, int value); }. When operations are known at compile time, a Map<String, AccountAction> provides type checking and a visible contract. Reflection earns its place when metadata or member names truly arrive at runtime.

Use OOP Basics in Java to design account abstractions through encapsulation, inheritance and polymorphism. Here BankAccount is deliberately narrow: it exists only to show how reflection locates and operates on runtime members. The short version is: Class<?> is the entry point; Constructor, Field and Method represent members; declared lookups can find a class's private members; access may still be denied; exact type tokens matter; and target exceptions arrive inside InvocationTargetException.

Continue with the Java course for structured learning, DSA using Java for interview-oriented problem solving, or the Coding & Skills category for a broader route. Keep direct calls as the default, and use reflection only when runtime discovery is the actual requirement.