Java Reflection API: Inspect and Use Classes at Runtime
The Java Reflection API lets a running program look at its own classes and use them without knowing them at compile time. With reflection you can list a class's fields and methods, read and change field values, call methods by name and create objects from a class name.
Frameworks depend on it. Spring creates your beans, JUnit finds your @Test methods and Jackson turns objects into JSON, all through reflection. You already used parts of it to read annotations in Java Custom Annotations and Java Annotation Targets. This lesson covers the core API step by step and ends with a small JSON serializer.
Java Reflection API Classes in java.lang.reflect
Reflection starts from a java.lang.Class object. Every other piece comes from the java.lang.reflect package.
| Type | Represents | Typical use |
|---|---|---|
Class<T> | A class, interface, enum, record, array or primitive | Entry point for everything else |
Field | A field | Read or write a value |
Method | A method | Call it with invoke |
Constructor<T> | A constructor | Create objects with newInstance |
Parameter | A method or constructor parameter | Read its type, name and annotations |
Modifier | Helper for public, static, final... | Decode getModifiers() |
Array | Helper for arrays of any type | Create and access arrays dynamically |
RecordComponent | A record component | Read record structure |
Proxy | A generated class implementing interfaces | Intercept method calls |
Getting a Class Object in Java
There are three ways to get a Class object. Which one you use depends on what you have: the type in source code, an object, or only a name.
import java.util.ArrayList;
import java.util.List;
public class GettingClass {
public static void main(String[] args) throws ClassNotFoundException {
Class<String> fromLiteral = String.class; // 1. class literal
List<String> courses = new ArrayList<>();
Class<?> fromObject = courses.getClass(); // 2. from an object
Class<?> fromName = Class.forName("java.time.LocalDate"); // 3. from a name
System.out.println(fromLiteral.getName());
System.out.println(fromObject.getName());
System.out.println(fromName.getSimpleName());
System.out.println(int.class.getName() + ", " + int[].class.getName() + ", " + String[].class.getName());
System.out.println("Same Class object? " + (fromLiteral == "hello".getClass()));
try {
Class.forName("com.gocourse.MissingClass");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e.getMessage());
}
}
}
Output:
java.lang.String
java.util.ArrayList
LocalDate
int, [I, [Ljava.lang.String;
Same Class object? true
ClassNotFoundException: com.gocourse.MissingClass
How it works:
String.classis checked by the compiler and gives a typedClass<String>.courses.getClass()returns the runtime class,ArrayList, even though the variable type isList.Class.forNametakes a fully qualified name as a string, so the class can be chosen while the program runs. A wrong name throws the checkedClassNotFoundException.- Each loaded class has exactly one
Classobject, so==comparison works. Arrays use JVM names such as[Iforint[].
| Way | Needs | Returns |
|---|---|---|
Type.class | The type at compile time | Class<Type> |
object.getClass() | An instance | Class<? extends StaticType> |
Class.forName("pkg.Name") | Only the name | Class<?>, may throw ClassNotFoundException |
Inspecting Fields With Reflection
Class has two families of lookup methods. The getX methods return public members, including inherited ones. The getDeclaredX methods return members of any access level, but only those declared in that exact class.
| Method | Access levels | Inherited members |
|---|---|---|
getFields() / getField(name) | public only | Yes |
getDeclaredFields() / getDeclaredField(name) | all | No |
getMethods() / getMethod(name, types...) | public only | Yes |
getDeclaredMethods() / getDeclaredMethod(name, types...) | all | No |
getConstructors() / getConstructor(types...) | public only | Never (constructors are not inherited) |
getDeclaredConstructors() / getDeclaredConstructor(types...) | all | Never |
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Person {
public String name = "Asha";
protected int age = 24;
}
class Student extends Person {
public String course = "Java";
private double fees = 4999.0;
static int totalStudents = 120;
}
public class InspectFields {
public static void main(String[] args) {
System.out.println("getFields() - public, including inherited:");
for (Field field : Student.class.getFields()) {
System.out.println(" " + field.getName() + " from " + field.getDeclaringClass().getSimpleName());
}
System.out.println("getDeclaredFields() - all access levels, this class only:");
for (Field field : Student.class.getDeclaredFields()) {
System.out.printf(" %-8s %-7s %s%n",
Modifier.toString(field.getModifiers()), field.getType().getSimpleName(), field.getName());
}
}
}
Output:
getFields() - public, including inherited:
course from Student
name from Person
getDeclaredFields() - all access levels, this class only:
public String course
private double fees
static int totalStudents
How it works:
getFields()finds the publiccourseinStudentand the publicnameinherited fromPerson. The protectedageand privatefeesare skipped.getDeclaredFields()finds all three fields ofStudent, whatever their access, but not the fields ofPerson.getModifiers()returns anintbit mask.Modifier.toStringturns it into readable keywords.
Reading and Writing Field Values
Field.get(object) reads a value and Field.set(object, value) writes one. For private fields you must first call setAccessible(true), which turns off Java's access check for that Field object.
import java.lang.reflect.Field;
class BankAccount {
private final String owner;
private double balance;
BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
@Override
public String toString() {
return owner + ": " + balance;
}
}
public class ReadWriteFields {
public static void main(String[] args) throws ReflectiveOperationException {
BankAccount account = new BankAccount("Karthik", 1500.0);
Field balanceField = BankAccount.class.getDeclaredField("balance");
try {
balanceField.get(account); // private: access check fails
} catch (IllegalAccessException e) {
System.out.println("Before setAccessible: " + e.getClass().getSimpleName());
}
balanceField.setAccessible(true);
double balance = balanceField.getDouble(account);
System.out.println("Read balance: " + balance);
balanceField.setDouble(account, balance + 500);
System.out.println("After set: " + account);
}
}
Output:
Before setAccessible: IllegalAccessException
Read balance: 1500.0
After set: Karthik: 2000.0
How it works:
getDeclaredField("balance")finds the private field, but finding is not the same as accessing. The firstgetthrowsIllegalAccessException.- After
setAccessible(true),getDoubleandsetDoublework. These typed variants avoid boxing; the generalgetandsetwork withObject. - For a static field, pass
nullas the object:field.get(null).
Note: Reflection bypasses encapsulation, so the class can no longer protect its own rules. Use it in frameworks and tools, not to reach into classes in everyday code.
Invoking Methods by Name
getMethod(name, parameterTypes...) finds a method by its exact signature. invoke(target, arguments...) calls it and returns the result as an Object.
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
class PriceCalculator {
public double applyDiscount(double price, int percent) {
return price - price * percent / 100;
}
public static String currency() {
return "INR";
}
private String secretFormula() {
return "internal formula";
}
}
public class InvokeMethods {
public static void main(String[] args) throws ReflectiveOperationException {
PriceCalculator calculator = new PriceCalculator();
Class<?> type = calculator.getClass();
Method discount = type.getMethod("applyDiscount", double.class, int.class);
Object result = discount.invoke(calculator, 2000.0, 15);
System.out.println(discount.getName() + " -> " + result);
Method currency = type.getMethod("currency");
System.out.println("static? " + Modifier.isStatic(currency.getModifiers())
+ ", result -> " + currency.invoke(null));
Method secret = type.getDeclaredMethod("secretFormula");
secret.setAccessible(true);
System.out.println(secret.getName() + " -> " + secret.invoke(calculator));
try {
type.getMethod("applyDiscount", double.class); // wrong parameter list
} catch (NoSuchMethodException e) {
System.out.println("NoSuchMethodException: " + e.getMessage());
}
}
}
Output:
applyDiscount -> 1700.0
static? true, result -> INR
secretFormula -> internal formula
NoSuchMethodException: PriceCalculator.applyDiscount(double)
How it works:
- Methods are found by name and parameter types, because overloaded methods share a name.
double.classandint.classdescribe the primitive parameters. invoke(calculator, 2000.0, 15)boxes the arguments, calls the method and boxes thedoubleresult into aDouble.- Static methods ignore the target, so
currency.invoke(null)is the normal way to call them. - A signature that does not exist throws
NoSuchMethodException, whose message shows what was searched for.
Exceptions Thrown by the Invoked Method
If the called method throws, invoke wraps that exception in an InvocationTargetException. The real exception is its cause.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Enrollment {
public void enroll(int seats) {
if (seats <= 0) {
throw new IllegalArgumentException("seats must be positive, got " + seats);
}
System.out.println("Enrolled " + seats + " seat(s)");
}
}
public class WrappedExceptions {
public static void main(String[] args) throws ReflectiveOperationException {
Method enroll = Enrollment.class.getMethod("enroll", int.class);
Enrollment enrollment = new Enrollment();
enroll.invoke(enrollment, 2);
try {
enroll.invoke(enrollment, 0);
} catch (InvocationTargetException e) {
System.out.println("Wrapper: " + e.getClass().getSimpleName());
System.out.println("Real cause: " + e.getCause());
}
try {
enroll.invoke(enrollment, "two"); // wrong argument type
} catch (IllegalArgumentException e) {
System.out.println("Bad argument: " + e.getMessage());
}
}
}
Output:
Enrolled 2 seat(s)
Wrapper: InvocationTargetException
Real cause: java.lang.IllegalArgumentException: seats must be positive, got 0
Bad argument: argument type mismatch
How it works:
- The
IllegalArgumentExceptionthrown insideenrollreaches the caller wrapped inInvocationTargetException. Always unwrap withgetCause()to see what really happened. - Passing
"two"for anintparameter fails before the method runs. ThatIllegalArgumentExceptioncomes from reflection itself, not fromenroll, so it is not wrapped.
| Exception | Meaning |
|---|---|
ClassNotFoundException | Class.forName could not find the class |
NoSuchFieldException / NoSuchMethodException | No member with that name or signature |
IllegalAccessException | The member is not accessible from here |
IllegalArgumentException | Wrong target object or argument types |
InvocationTargetException | The invoked method or constructor threw; see getCause() |
InaccessibleObjectException | setAccessible blocked by the module system |
All the checked ones extend ReflectiveOperationException, so throws ReflectiveOperationException covers them in one line.
Creating Objects With Constructors
Constructor.newInstance(arguments...) creates an object, just like new. Choose the constructor by its parameter types.
import java.lang.reflect.Constructor;
class Course {
private final String title;
private final int hours;
public Course() {
this("Untitled", 0);
}
public Course(String title, int hours) {
this.title = title;
this.hours = hours;
}
@Override
public String toString() {
return title + " (" + hours + "h)";
}
}
public class UseConstructors {
public static void main(String[] args) throws ReflectiveOperationException {
System.out.println("Public constructors: " + Course.class.getConstructors().length);
Constructor<Course> noArgs = Course.class.getDeclaredConstructor();
Course empty = noArgs.newInstance();
System.out.println("No-arg: " + empty);
Constructor<Course> full = Course.class.getConstructor(String.class, int.class);
Course reflection = full.newInstance("Java Reflection", 6);
System.out.println("Two-arg: " + reflection + ", parameters = " + full.getParameterCount());
}
}
Output:
Public constructors: 2
No-arg: Untitled (0h)
Two-arg: Java Reflection (6h), parameters = 2
How it works:
getDeclaredConstructor()with no arguments finds the no-arg constructor, andnewInstance()runs it.getConstructor(String.class, int.class)picks the two-argument constructor. The typedConstructor<Course>meansnewInstancereturns aCoursewith no cast.- Creating objects from class names, factories and plugin loading are covered fully in Java Dynamic Objects.
Working With Arrays Using java.lang.reflect.Array
You cannot write new T[size] for an unknown type. The Array helper creates and accesses arrays of any component type, including primitives.
import java.lang.reflect.Array;
import java.util.Arrays;
public class ReflectArrays {
public static void main(String[] args) {
Object scores = Array.newInstance(int.class, 3); // same as new int[3]
Array.setInt(scores, 0, 90);
Array.setInt(scores, 1, 75);
Array.setInt(scores, 2, 88);
System.out.println("Length: " + Array.getLength(scores));
System.out.println(Arrays.toString((int[]) scores));
System.out.println("Component type: " + scores.getClass().getComponentType());
String[] names = (String[]) Array.newInstance(String.class, 2);
Array.set(names, 0, "Asha");
Array.set(names, 1, "Ravi");
System.out.println(Arrays.toString(names));
}
}
Output:
Length: 3
[90, 75, 88]
Component type: int
[Asha, Ravi]
How it works:
Array.newInstance(int.class, 3)returns anObjectthat really is anint[], so the cast succeeds.setIntandgetLengthwork on any array type without knowing it at compile time. This is how generic code such asArrayList.toArray(T[])builds arrays of the right type.
Reflection and the Java Module System
Since Java 9, setAccessible(true) only works on packages that are open to your code. Your own classes on the classpath are always open, but JDK internals are not.
import java.lang.reflect.Field;
public class ModuleLimits {
public static void main(String[] args) throws NoSuchFieldException {
Field value = String.class.getDeclaredField("value");
System.out.println("Found field: " + value.getType().getSimpleName() + " " + value.getName());
try {
value.setAccessible(true);
} catch (RuntimeException e) {
System.out.println(e.getClass().getName());
}
System.out.println("trySetAccessible: " + value.trySetAccessible());
}
}
Output:
Found field: byte[] value
java.lang.reflect.InaccessibleObjectException
trySetAccessible: false
How it works:
- Finding the private
valuefield ofStringis allowed; reflection can always describe a class. - Accessing it is not:
java.basedoes not openjava.langto your code, sosetAccessiblethrowsInaccessibleObjectException. trySetAccessible()does the same check but returnsfalseinstead of throwing, which is handy in libraries.
Note: In your own modular applications, use
opens com.example.model;inmodule-info.javato allow frameworks to reflect into a package, as explained in module-info in Java.
Real-World Example: A Mini JSON Serializer
Libraries such as Jackson and Gson convert any object to JSON without you writing per-class code. They do it with reflection: walk the fields, read each value and handle it by type. This example builds a small version.
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.List;
import java.util.StringJoiner;
class Address {
private final String city;
private final String pincode;
Address(String city, String pincode) {
this.city = city;
this.pincode = pincode;
}
}
class Instructor {
private static int instructorCount = 0; // static: not part of the object
private final String name;
private final int experienceYears;
private final boolean verified;
private final Address address;
private final List<String> skills;
private transient String passwordHash = "x9f2k"; // transient: never serialized
Instructor(String name, int experienceYears, boolean verified, Address address, List<String> skills) {
this.name = name;
this.experienceYears = experienceYears;
this.verified = verified;
this.address = address;
this.skills = skills;
instructorCount++;
}
}
class JsonWriter {
static String toJson(Object value) throws IllegalAccessException {
if (value == null) {
return "null";
}
if (value instanceof String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
if (value instanceof Number || value instanceof Boolean) {
return value.toString();
}
if (value instanceof Collection<?> items) {
StringJoiner array = new StringJoiner(", ", "[", "]");
for (Object item : items) {
array.add(toJson(item));
}
return array.toString();
}
// any other object: reflect over its fields
StringJoiner object = new StringJoiner(", ", "{", "}");
for (Field field : value.getClass().getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
continue;
}
field.setAccessible(true);
object.add("\"" + field.getName() + "\": " + toJson(field.get(value)));
}
return object.toString();
}
}
public class MiniJson {
public static void main(String[] args) throws IllegalAccessException {
Instructor priya = new Instructor("Priya \"PR\" Raman", 8, true,
new Address("Chennai", "600042"), List.of("Java", "Spring Boot", "SQL"));
Instructor arun = new Instructor("Arun", 2, false, null, List.of());
System.out.println(JsonWriter.toJson(priya));
System.out.println(JsonWriter.toJson(arun));
System.out.println(JsonWriter.toJson(List.of(new Address("Madurai", "625001"))));
}
}
Output:
{"name": "Priya \"PR\" Raman", "experienceYears": 8, "verified": true, "address": {"city": "Chennai", "pincode": "600042"}, "skills": ["Java", "Spring Boot", "SQL"]}
{"name": "Arun", "experienceYears": 2, "verified": false, "address": null, "skills": []}
[{"city": "Madurai", "pincode": "625001"}]
How it works:
- Simple values first. Strings get quotes and escaped
"characters; numbers and booleans print as they are;nullbecomesnull. - Collections. Any
Collectionbecomes a JSON array, and each element is converted with a recursivetoJsoncall. CheckingCollectionbefore the reflection branch matters, becauseList.ofreturns a JDK-internal class whose fields we must not and cannot reflect into. - Objects. For everything else,
getDeclaredFields()lists the fields.staticfields belong to the class, not the object, andtransientmarks fields that must not be saved, so both are skipped. That keepspasswordHashout of the output. - Private access.
setAccessible(true)works becauseInstructorandAddressare in our own unnamed module. - Recursion. The
addressfield holds anAddress, sotoJsonreflects over it in turn, producing nested JSON. Whenaddressisnull, the first check printsnull. - Field order. The standard JVM returns declared fields in source order, which is why the keys follow the class. The specification does not guarantee this, so real libraries let you fix the order with annotations such as Jackson's
@JsonPropertyOrder.
With about 40 lines of reflection, one method serializes classes it has never seen. The next lesson, Java Class Metadata, looks at everything else a Class object can tell you: names, modifiers, superclasses, interfaces and generic types.