Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
Use Java reflection to inspect any class at runtime: Field, Method, Constructor and RecordComponent, getDeclaredFields vs getFields, Modifier and AccessFlag, sealed and record metadata, reading and writing fields with setAccessible, module restrictions, and a generic toString.
kvi5hnuCode Sprout team member13 min readOn this page
In the previous article you met the Class object, the runtime description of a type. Now we look inside it: which fields, methods and constructors does a class have, with which types and modifiers? Then we go one step further and read and write the fields of live objects, even ones whose classes didn't exist when your code was compiled. This is the machinery behind debuggers, JSON mappers, ORMs, dependency injection containers and test frameworks.
The Members of a Class: Field, Method and Constructor
Three classes in the java.lang.reflect package describe the parts of a class:
Fielddescribes a field.getType()returns anotherClassobject for the field's type.Methoddescribes a method. It reports the parameter types (getParameterTypes()), the return type (getReturnType()) and the declared exceptions (getExceptionTypes()).Constructordescribes a constructor, with parameter and exception types.
Since Java 16 there's a fourth: RecordComponent, which describes a component of a record with getName(), getType() and getAccessor() (the Method that reads it).
All of them have a getName method and a getDeclaringClass method that returns the class declaring the member.

Public versus declared members
The Class class offers two families of lookup methods:
| Method | Returns |
|---|---|
getFields(), getMethods(), getConstructors() | The public members, including public members inherited from superclasses (and, for methods, superinterfaces) |
getDeclaredFields(), getDeclaredMethods(), getDeclaredConstructors() | All members declared in this class: public, protected, package access and private, but no inherited members |
There are also singular forms that look up one member by name and parameter types: getField("name"), getDeclaredField("name"), getMethod("giveRaise", double.class), getDeclaredConstructor(String.class, double.class). They throw NoSuchFieldException or NoSuchMethodException if there's no match. The array-returning methods return a zero-length array if there are no members, or if the Class object describes a primitive type or an array type.
Modifiers: the Modifier class and AccessFlag
Field, Method, Constructor and Class all have a getModifiers method that returns an int, with various bits turned on and off for modifiers such as public and static. You analyze it with the static methods of the java.lang.reflect.Modifier class:
if (Modifier.isStatic(m.getModifiers())) . . .
String text = Modifier.toString(m.getModifiers()); // e.g. "public static final"
There are tests for every modifier: isAbstract, isFinal, isInterface, isNative, isPrivate, isProtected, isPublic, isStatic, isStrict, isSynchronized, isTransient and isVolatile.
Java 20 added a more type-safe alternative: accessFlags() returns a Set<AccessFlag>, using the enum java.lang.reflect.AccessFlag:
if (m.accessFlags().contains(AccessFlag.STATIC)) . . .
(Some older printed material shows Modifiers.isStatic, with an "s". The class is called Modifier.)
Class-level information
Besides members, the Class object tells you about the type itself:
| Method | Since | Purpose |
|---|---|---|
getSuperclass() | 1.0 | Superclass, or null for Object, interfaces and primitive types |
getInterfaces() | 1.0 | Directly implemented (or, for interfaces, extended) interfaces |
isInterface(), isEnum(), isArray(), isPrimitive() | 1.0–1.5 | What kind of type this is |
isRecord(), getRecordComponents() | 16 | Records and their components (null if not a record) |
isSealed(), getPermittedSubclasses() | 17 | Sealed types and their permits list |
getPackageName() | 9 | Package; for arrays, the element type's package; "java.lang" for primitives |
Printing the Structure of Any Class
The following program reads a class name, then prints the class's declaration: modifiers, kind, superclass, interfaces, permitted subclasses, record components, and the signatures of all declared constructors, methods and fields. Edit the stdin to try Team, Circle, or a JDK class such as java.lang.Double. It then shows the sealed interface Shape and the record Point.
The second half of main previews the next section, inspecting objects.
import java.lang.reflect.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws ReflectiveOperationException {
String name = args.length > 0 ? args[0] : new Scanner(System.in).next();
printClass(Class.forName(name));
System.out.println();
printClass(Class.forName("Shape"));
printClass(Class.forName("Point"));
System.out.println();
// inspecting objects
var omar = new Employee("Omar Haddad", 52000);
Field f = Employee.class.getDeclaredField("name");
try {
System.out.println(f.get(omar));
} catch (IllegalAccessException ex) {
System.out.println("IllegalAccessException: name is private");
}
f.setAccessible(true);
System.out.println(f.get(omar));
Field salary = Employee.class.getDeclaredField("salary");
salary.setAccessible(true);
salary.setDouble(omar, salary.getDouble(omar) + 5000);
System.out.println(omar.getSalary());
System.out.println(Modifier.toString(salary.getModifiers()) + " | " + salary.accessFlags());
System.out.println(new FieldDumper().toString(omar));
var team = new Team("core", new Employee[] { omar, new Employee("Priya Nair", 68000) });
team.self = team;
System.out.println(new FieldDumper().toString(team));
System.out.println(new FieldDumper().toString(new int[] {1, 4, 9}));
try {
System.out.println(new FieldDumper().toString(new ArrayList<>(List.of(1, 4, 9))));
} catch (InaccessibleObjectException ex) {
System.out.println("InaccessibleObjectException: java.base does not open java.util");
}
}
static void printClass(Class<?> cl) {
// Modifier.toString includes "abstract interface" for interfaces; we print the kind ourselves
String modifiers = Modifier.toString(cl.getModifiers() & ~Modifier.INTERFACE & (cl.isInterface() ? ~Modifier.ABSTRACT : ~0));
if (!modifiers.isEmpty()) System.out.print(modifiers + " ");
if (cl.isSealed()) System.out.print("sealed ");
if (cl.isEnum()) System.out.print("enum ");
else if (cl.isRecord()) System.out.print("record ");
else if (cl.isInterface()) System.out.print("interface ");
else System.out.print("class ");
System.out.print(cl.getName());
Class<?> supercl = cl.getSuperclass();
if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName());
Class<?>[] interfaces = cl.getInterfaces();
for (int i = 0; i < interfaces.length; i++)
System.out.print((i == 0 ? (cl.isInterface() ? " extends " : " implements ") : ", ") + interfaces[i].getName());
if (cl.isSealed()) {
Class<?>[] permitted = cl.getPermittedSubclasses();
for (int i = 0; i < permitted.length; i++)
System.out.print((i == 0 ? " permits " : ", ") + permitted[i].getName());
}
System.out.println(" {");
if (cl.isRecord())
for (RecordComponent rc : cl.getRecordComponents())
System.out.println(" // component " + rc.getType().getName() + " " + rc.getName()
+ ", accessor " + rc.getAccessor().getName() + "()");
for (Constructor<?> c : sorted(cl.getDeclaredConstructors()))
System.out.println(" " + prefix(c.getModifiers()) + c.getName() + "(" + params(c.getParameterTypes()) + ");");
for (Method m : sorted(cl.getDeclaredMethods()))
System.out.println(" " + prefix(m.getModifiers()) + m.getReturnType().getName() + " " + m.getName()
+ "(" + params(m.getParameterTypes()) + ")" + throwsClause(m.getExceptionTypes()) + ";");
for (Field f : sorted(cl.getDeclaredFields()))
System.out.println(" " + prefix(f.getModifiers()) + f.getType().getName() + " " + f.getName() + ";");
System.out.println("}");
}
// the order of getDeclaredXxx results is unspecified, so sort for stable output
static <T extends Member> List<T> sorted(T[] members) {
var list = new ArrayList<>(Arrays.asList(members));
list.sort(Comparator.comparing((T m) -> m.getName()).thenComparing(Object::toString));
return list;
}
static String prefix(int mod) {
String s = Modifier.toString(mod);
return s.isEmpty() ? "" : s + " ";
}
static String params(Class<?>[] types) {
var sj = new StringJoiner(", ");
for (Class<?> t : types) sj.add(t.getTypeName());
return sj.toString();
}
static String throwsClause(Class<?>[] types) {
return types.length == 0 ? "" : " throws " + params(types);
}
}
class Employee {
private String name;
private double salary;
public static int nextId = 1;
public Employee(String name, double salary) { this.name = name; this.salary = salary; }
private Employee() { this("", 0); }
public String getName() { return name; }
public double getSalary() { return salary; }
public void giveRaise(double pct) { salary += salary * pct / 100; }
protected Object copy() throws CloneNotSupportedException { return super.clone(); }
}
class Team {
String name;
Employee[] members;
Team self;
Team(String name, Employee[] members) { this.name = name; this.members = members; }
}
sealed interface Shape permits Point, Circle { double area(); }
record Point(int x, int y) implements Shape { public double area() { return 0; } }
final class Circle implements Shape {
private final double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}
class FieldDumper {
private final List<Object> visited = new ArrayList<>();
public String toString(Object obj) throws ReflectiveOperationException {
if (obj == null) return "null";
for (Object v : visited) if (v == obj) return "..."; // compare identity, not equals
visited.add(obj);
Class<?> cl = obj.getClass();
if (cl == String.class) return (String) obj;
if (cl.isArray()) {
var r = new StringBuilder(cl.getComponentType().getName() + "[]{");
for (int i = 0; i < Array.getLength(obj); i++) {
if (i > 0) r.append(",");
Object val = Array.get(obj, i);
if (cl.getComponentType().isPrimitive()) r.append(val);
else r.append(toString(val));
}
return r.append("}").toString();
}
var r = new StringBuilder(cl.getName());
// inspect the fields of this class and all superclasses
do {
r.append("[");
Field[] fields = cl.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
boolean first = true;
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers())) continue;
if (!first) r.append(",");
first = false;
r.append(f.getName()).append("=");
Object val = f.get(obj);
if (f.getType().isPrimitive()) r.append(val);
else r.append(toString(val));
}
r.append("]");
cl = cl.getSuperclass();
} while (cl != null);
return r.toString();
}
}
class Employee {
private Employee();
public Employee(java.lang.String, double);
protected java.lang.Object copy() throws java.lang.CloneNotSupportedException;
public java.lang.String getName();
public double getSalary();
public void giveRaise(double);
private java.lang.String name;
public static int nextId;
private double salary;
}
sealed interface Shape permits Point, Circle {
public abstract double area();
}
final record Point extends java.lang.Record implements Shape {
// component int x, accessor x()
// component int y, accessor y()
Point(int, int);
public double area();
public final boolean equals(java.lang.Object);
public final int hashCode();
public final java.lang.String toString();
public int x();
public int y();
private final int x;
private final int y;
}
IllegalAccessException: name is private
Omar Haddad
57000.0
private | [PRIVATE]
Employee[name=Omar Haddad,salary=57000.0][]
Team[name=core,members=Employee[]{Employee[name=Omar Haddad,salary=57000.0][],Employee[name=Priya Nair,salary=68000.0][]},self=...][]
int[]{1,4,9}
InaccessibleObjectException: java.base does not open java.util
Some things to notice in the output:
- The record
Pointreveals everything the compiler generated: the canonical constructor, the accessorsx()andy(), theprivate finalfields, and thefinalmethodsequals,hashCodeandtoString. Its superclass isjava.lang.Record. - The interface method
areashows up aspublic abstract: interface methods are implicitly both. getParameterTypesreports only types, not parameter names. Parameter names are available throughMethod.getParameters(), but only if the class was compiled withjavac -parameters. Otherwise you getarg0,arg1, …
What's remarkable is that this program can analyze any class the JVM can load, not just the ones available when it was compiled. Run it on java.lang.Double and you'll see dozens of methods, including some you never call directly, such as describeConstable (from the constant API) and a volatile compareTo(java.lang.Object). That odd one is a bridge method generated by the compiler to make generics work, and in Modifier.toString the bridge bit happens to print as volatile. We'll use this program in the next part to peek inside the inner classes the compiler generates.
Inspecting Objects at Runtime
You've seen how to find out the names and types of the fields of any class:
- Get the corresponding
Classobject. - Call
getDeclaredFieldson it.
Now let's look at the contents of the fields. It's easy to read a field whose name and type you know when you write the program. Reflection lets you read fields of objects whose classes weren't known at compile time.
The key method is get in the Field class. If f is a Field and obj is an object of the class that declares f, then f.get(obj) returns the current value of that field in obj:
var omar = new Employee("Omar Haddad", 52000);
Class<?> cl = omar.getClass(); // the class object representing Employee
Field f = cl.getDeclaredField("name"); // the name field of the Employee class
Object v = f.get(omar); // the value of the name field of omar: "Omar Haddad"
You can also set values: f.set(obj, value) sets the field f of obj to value.
For primitive fields, get returns a wrapper object (a Double for a double field), and set unwraps one. There are also primitive-specific methods such as getDouble and setDouble, which avoid boxing.
Access control and setAccessible
There's a catch in the code above. name is a private field, so f.get(omar) throws an IllegalAccessException. By default, reflection respects Java access control: you can find out which fields an object has, but you can't read or write private ones.
You can override access control by calling setAccessible(true) on a Field, Method or Constructor:
f.setAccessible(true); // now OK to call f.get(omar)
setAccessible is a method of AccessibleObject, the common superclass of Field, Method and Constructor. The static convenience method AccessibleObject.setAccessible(array, true) makes a whole array of members accessible. The feature exists for debuggers, persistent storage, serialization and similar tools. trySetAccessible() (Java 9) returns false instead of throwing if access can't be granted. To ask without changing anything, call canAccess(obj) (Java 9): field.canAccess(omar) tells you whether code at this point could currently read omar's field through reflection (pass null for static members). It replaces the deprecated isAccessible(), whose name misled people into thinking it reported the member's visibility. It only ever reported the setAccessible flag.
The module system says no
setAccessible itself can be denied. The module system (covered in the modules part) lets a module keep its packages closed to deep reflection. In the past a security manager could deny access too, but the Security Manager was deprecated in Java 17 and permanently disabled in Java 24.

The history matters, because you'll still see old advice on the web:
| Java version | Reflecting into JDK internals (e.g. ArrayList.elementData) |
|---|---|
| 8 and earlier | Allowed |
| 9 to 15 | Allowed, with "WARNING: An illegal reflective access operation has occurred" |
| 16 | Denied by default (JEP 396); --illegal-access=permit restored the old behavior |
| 17 and later | Denied, and the --illegal-access option is gone (JEP 403): InaccessibleObjectException |
To get such a program running, you open the packages to the "unnamed module" (all class path code) on the command line:
java --add-opens java.base/java.util=ALL-UNNAMED \
--add-opens java.base/java.lang=ALL-UNNAMED \
com.example.FieldDumperTest
For your own modular code, you'd write opens com.myapp.model; in module-info.java so a framework like Hibernate or Jackson can reflect on your entity classes. Classes on the class path, like all the programs in this course so far, are fully open to each other, which is why the demo above can read Employee.salary after setAccessible(true).
A Generic toString Method
Reflection lets you write one toString that works for any class. The FieldDumper in the program above uses getDeclaredFields to obtain all instance fields, AccessibleObject.setAccessible to make them accessible, and then, for each field, gets the name and value. Each value is turned into a string by recursively calling toString. It walks up through the superclasses too, printing one [...] group per class (Object has no fields, so you see a trailing []).
It has to deal with two complications:
- Cycles: an object can refer to itself, directly or indirectly (
team.self = team). The analyzer keeps a list of visited objects and prints...for one it has already seen. It compares with==rather thanequals, because two distinct but equal objects aren't a cycle. - Arrays: they have no fields. The analyzer uses
cl.isArray(),getComponentType()and thejava.lang.reflect.Arrayclass to walk the elements. The next article coversArrayin detail.
You could even implement your own toString methods like this:
public String toString() {
try {
return new FieldDumper().toString(this);
} catch (ReflectiveOperationException e) {
return super.toString();
}
}
That's a hassle-free universal toString, and in the early days of Java it was a popular trick. Before you get too excited, remember the module restrictions: the analyzer can't look inside ArrayList or Integer any more without --add-opens, as the last line of the output shows. Reflective access to internals is a privilege the JDK is steadily taking away. For your own classes, records or an IDE-generated toString are usually the better choice.
Common questions
What is the difference between getMethods() and getDeclaredMethods()?
getMethods() returns all public methods, including inherited ones from superclasses and interfaces. getDeclaredMethods() returns all methods declared in this class (public, protected, package and private) but no inherited ones. Walk up getSuperclass() if you need every method of a hierarchy.
How can I get parameter names through reflection?
Compile with javac -parameters. Then Method.getParameters() returns Parameter objects whose getName() gives the real names. Without the flag, you get arg0, arg1 and so on. Spring, Jackson and many other frameworks recommend or rely on -parameters.
Why do I get InaccessibleObjectException when calling setAccessible(true)?
The target is in a module package that isn't opened to your code. This is the case for most JDK internals, such as the fields of ArrayList. Add --add-opens module/package=ALL-UNNAMED as a temporary workaround, or better, use public APIs. For your own modules, add opens to module-info.java.
Is reflection on records special?
Records have dedicated API: isRecord() and getRecordComponents() give the components in declaration order, with their accessors and annotations. Their final fields can't be changed through Field.set, even after setAccessible(true). That is enforced for records, hidden classes and, increasingly, for all final fields.
Should my application code use reflection? Rarely. It is valuable in frameworks, tools, plugin systems and tests. In business logic, interfaces, lambdas and pattern matching give you the same flexibility with compile-time checking and better performance.
Summary
Field,Method,ConstructorandRecordComponentdescribe the members of a class.getName,getModifiers,accessFlagsandgetDeclaringClasswork on all members.getFields/getMethods/getConstructorsreturn public members, including inherited ones.getDeclaredXxxreturns all members of the class itself. The order is unspecified.- Analyze modifiers with
Modifier.isStatic(...),Modifier.toString(...), or theAccessFlagset (Java 20). Classreports records (isRecord,getRecordComponents), sealed types (isSealed,getPermittedSubclasses), enums, interfaces and arrays.f.get(obj)andf.set(obj, value)read and write fields. Private members needsetAccessible(true).- Since Java 17, packages of named modules (including the JDK) are closed to deep reflection unless opened with
opensor--add-opens. Java 26 warns on mutating final fields. - A generic reflective
toStringmust handle cycles and arrays. It's a nice demo, but not a substitute for well-designedtoStringmethods.
Practice Questions
What's the difference between getMethods() and getDeclaredMethods() for a class Manager extends Employee?
getMethods() returns all public methods of Manager, including public ones inherited from Employee and Object. getDeclaredMethods() returns every method declared in Manager itself, of any access level, but no inherited ones.
How do you test with reflection whether a Method m is static, in two ways?
Modifier.isStatic(m.getModifiers()), or m.accessFlags().contains(AccessFlag.STATIC) since Java 20.
f is the private field salary of Employee. What happens with f.get(omar) before and after f.setAccessible(true), when Employee is on the class path?
Before, IllegalAccessException, because reflection respects access control. After, it returns the salary boxed as a Double. Class path code isn't protected by module encapsulation, so setAccessible succeeds.
A Java 8 library worked fine but fails on Java 21 with InaccessibleObjectException. Why, and what are the fixes?
It reflects into JDK internals, which strong encapsulation has denied by default since Java 16/17. The proper fix is to stop using internals and use public API (or update the library). The workaround is --add-opens module/package=ALL-UNNAMED on the command line.
Why does the FieldDumper use == instead of a HashSet or contains (which uses equals) to detect visited objects?
A cycle means the same object is reached again, which is identity. Distinct objects that happen to be equal must still be printed. Also, equals and hashCode of arbitrary classes might themselves be expensive, buggy, or recurse. IdentityHashMap or Collections.newSetFromMap(new IdentityHashMap<>()) would be an efficient alternative.
Write code that prints the name and type of every component of any record object rec.
for (RecordComponent rc : rec.getClass().getRecordComponents()) {
Object value = rc.getAccessor().invoke(rec);
System.out.println(rc.getName() + ": " + rc.getType().getSimpleName() + " = " + value);
}
The accessor methods are public, so no setAccessible is needed when the record class itself is accessible.
Previous: Java Reflection: The Class Class, Exceptions Primer and Loading Resources
Next: Java Reflection: Invoking Methods and Writing Generic Array Code
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.