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

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", asksBankAccount.classfor a method with parameter typeint.class, then invokes it with25.
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 |
|
Private |
|
Private |
|
Inherited public |
|
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.

Worked example: construct, read, change and invoke
Save this complete program as ReflectionDemo.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:
javac ReflectionDemo.java
java ReflectionDemoThe exact output is:
class=BankAccount
owner=Asha
opening=1000
after-set=1200
bonus=300
final-balance=1500
IllegalArgumentException: percent must be >= 0Trace it in five moves:
Acquire the
Class<?>metadata entry point.Look up the constructor by its exact
String, intsignature.Create an
Objectwhose opening balance is1000.Use
getIntandsetIntto read the primitive field and change it to1200.Find
addBonus(int)and invoke it.Method.invokereturnsObject, so(int)unboxes the returnedInteger.
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.

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:
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 |
|---|---|---|
| Wrong binary name in | Check the full package and class name |
|
| Use the declared spelling |
|
| Match the exact parameter token |
| Private member found, access not enabled | Check |
| Receiver or argument type does not match | Check receiver and signature |
|
| Inspect |
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:
Add private
int limit = 2000, find it withgetDeclaredField("limit"), set it to2400, and printlimit=2400.Request
getDeclaredMethod("addBonus", Integer.class), predictNoSuchMethodException, then fix it withint.class.Change
-5to-10. The cause remainsIllegalArgumentExceptionwith the same message, and balance remains1500.Stream
type.getDeclaredFields(), mapField::getName, sort, and expectbalancethenowner.
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.
Keep learning
Annotations in Java Tutorial: Custom Metadata, Retention and Reflection Examples
Create a custom Java annotation from zero, inspect its values through reflection, and learn how retention, targets and defaults control the result.
Records and Sealed Classes in Java: Runnable Examples and Rules
Learn when to use a Java record and when to seal a hierarchy. Compile two complete examples, trace their output, and fix the mistakes learners often make.
Encapsulation in Java: Build Safer Classes with Runnable Examples
Learn how a Java class can protect valid state through private fields, behaviour methods, validation before mutation, and defensive collection copies.
OOP Basics in Java: Classes, Objects and the Four Pillars with Runnable Examples
Connect Java's OOP syntax to design decisions with a complete Account example. Trace two objects through validation, overriding and runtime dispatch to exact output.





