Java Reflection API: Inspect and Use Classes at Runtime

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 237 of 306

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.

TypeRepresentsTypical use
Class<T>A class, interface, enum, record, array or primitiveEntry point for everything else
FieldA fieldRead or write a value
MethodA methodCall it with invoke
Constructor<T>A constructorCreate objects with newInstance
ParameterA method or constructor parameterRead its type, name and annotations
ModifierHelper for public, static, final...Decode getModifiers()
ArrayHelper for arrays of any typeCreate and access arrays dynamically
RecordComponentA record componentRead record structure
ProxyA generated class implementing interfacesIntercept 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.class is checked by the compiler and gives a typed Class<String>.
  • courses.getClass() returns the runtime class, ArrayList, even though the variable type is List.
  • Class.forName takes a fully qualified name as a string, so the class can be chosen while the program runs. A wrong name throws the checked ClassNotFoundException.
  • Each loaded class has exactly one Class object, so == comparison works. Arrays use JVM names such as [I for int[].
WayNeedsReturns
Type.classThe type at compile timeClass<Type>
object.getClass()An instanceClass<? extends StaticType>
Class.forName("pkg.Name")Only the nameClass<?>, 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.

MethodAccess levelsInherited members
getFields() / getField(name)public onlyYes
getDeclaredFields() / getDeclaredField(name)allNo
getMethods() / getMethod(name, types...)public onlyYes
getDeclaredMethods() / getDeclaredMethod(name, types...)allNo
getConstructors() / getConstructor(types...)public onlyNever (constructors are not inherited)
getDeclaredConstructors() / getDeclaredConstructor(types...)allNever
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 public course in Student and the public name inherited from Person. The protected age and private fees are skipped.
  • getDeclaredFields() finds all three fields of Student, whatever their access, but not the fields of Person.
  • getModifiers() returns an int bit mask. Modifier.toString turns 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 first get throws IllegalAccessException.
  • After setAccessible(true), getDouble and setDouble work. These typed variants avoid boxing; the general get and set work with Object.
  • For a static field, pass null as 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.class and int.class describe the primitive parameters.
  • invoke(calculator, 2000.0, 15) boxes the arguments, calls the method and boxes the double result into a Double.
  • 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 IllegalArgumentException thrown inside enroll reaches the caller wrapped in InvocationTargetException. Always unwrap with getCause() to see what really happened.
  • Passing "two" for an int parameter fails before the method runs. That IllegalArgumentException comes from reflection itself, not from enroll, so it is not wrapped.
ExceptionMeaning
ClassNotFoundExceptionClass.forName could not find the class
NoSuchFieldException / NoSuchMethodExceptionNo member with that name or signature
IllegalAccessExceptionThe member is not accessible from here
IllegalArgumentExceptionWrong target object or argument types
InvocationTargetExceptionThe invoked method or constructor threw; see getCause()
InaccessibleObjectExceptionsetAccessible 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, and newInstance() runs it.
  • getConstructor(String.class, int.class) picks the two-argument constructor. The typed Constructor<Course> means newInstance returns a Course with 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 an Object that really is an int[], so the cast succeeds.
  • setInt and getLength work on any array type without knowing it at compile time. This is how generic code such as ArrayList.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 value field of String is allowed; reflection can always describe a class.
  • Accessing it is not: java.base does not open java.lang to your code, so setAccessible throws InaccessibleObjectException.
  • trySetAccessible() does the same check but returns false instead of throwing, which is handy in libraries.

Note: In your own modular applications, use opens com.example.model; in module-info.java to 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:

  1. Simple values first. Strings get quotes and escaped " characters; numbers and booleans print as they are; null becomes null.
  2. Collections. Any Collection becomes a JSON array, and each element is converted with a recursive toJson call. Checking Collection before the reflection branch matters, because List.of returns a JDK-internal class whose fields we must not and cannot reflect into.
  3. Objects. For everything else, getDeclaredFields() lists the fields. static fields belong to the class, not the object, and transient marks fields that must not be saved, so both are skipped. That keeps passwordHash out of the output.
  4. Private access. setAccessible(true) works because Instructor and Address are in our own unnamed module.
  5. Recursion. The address field holds an Address, so toJson reflects over it in turn, producing nested JSON. When address is null, the first check prints null.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Reflection API: Inspect and Use Classes at Runtime and get answers drawn from it.

Signed-in readers only.