Java Reflection: Fields, Methods and Constructors at Runtime

Reflection lets a running Java program look at classes it did not know about when it was compiled: list their fields and methods, read and write values, call methods, create objects and read annotations. This guide explains each part of the java.lang.reflect API with complete, runnable programs and their real output, then covers generics, the module system, performance, and when not to use reflection.

Contents

What Reflection Is For

In ordinary Java code, every class, method and field you use is spelled out in the source: new Order(), order.getTotal(). The compiler checks that each one exists and that the types fit, so a misspelt method name is a compile error, not a crash in production.

Reflection lets a program use classes that are not spelled out in its source. It can take any object, ask its class which fields and methods it has, and then read those fields or call those methods by name. The program below makes the same call both ways, then turns an object into JSON without knowing its class, which is exactly what Jackson does.

Java
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DirectVsReflective {

    public static class Order {
        private final int id = 7;
        private final double total = 19.99;

        public double getTotal() {
            return total;
        }
    }

    public static void main(String[] args) throws Exception {
        Order order = new Order();

        // Direct: the method name is in the source, and the compiler checks it
        System.out.println("direct:     " + order.getTotal());

        // Reflective: the method name is just a String, looked up while running
        Method getter = order.getClass().getMethod("getTotal");
        System.out.println("reflective: " + getter.invoke(order));

        // What a JSON library does with an object it has never seen
        StringBuilder json = new StringBuilder("{");
        for (Field field : order.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            if (json.length() > 1) json.append(",");
            json.append('"').append(field.getName()).append("\":");
            json.append(field.get(order));
        }
        System.out.println("as JSON:    " + json.append("}"));

        // A typo compiles fine and only fails when this line runs
        try {
            order.getClass().getMethod("getTotla");
        } catch (NoSuchMethodException e) {
            System.out.println("typo:       NoSuchMethodException: " + e.getMessage());
        }
    }
}

Output:

Output
direct:     19.99
reflective: 19.99
as JSON:    {"id":7,"total":19.99}
typo:       NoSuchMethodException: DirectVsReflective$Order.getTotla()

The direct and reflective calls give the same result, but they fail differently. With the direct call, a typo such as getTotla() would not compile. With reflection, the name is just a String, so the same typo compiles and only fails with NoSuchMethodException when that line runs. The JSON loop never mentions id or total: it discovers them at runtime, so it works for any class.

You meet reflection every day, mostly inside libraries:

  • Jackson and Gson read and write fields to convert objects to and from JSON.
  • JUnit finds methods annotated with @Test and calls them.
  • Spring creates beans through their constructors and fills @Autowired dependencies.
  • Hibernate maps table columns to entity fields.

The price is that the compiler can no longer check anything: a wrong method name or argument type only fails when that line runs. That trade-off is the theme of this page.

Every API used below lives in java.lang.Class and the java.lang.reflect package. All examples are complete programs, tested on Java 21.

Getting a Class Object

Every reflective operation starts from a Class object. The JVM creates exactly one per loaded class, so all three ways below return the same object.

HowUse it whenRuns static initialisers?
String.classyou know the type while writing the codeno
obj.getClass()you have an object and want its real (runtime) typealready ran when the object was created
Class.forName("java.lang.String")the class name is only known at runtime, for example from a config fileyes
Java
import java.util.ArrayList;
import java.util.List;

public class ClassObjects {

    static class Plugin {
        static {
            System.out.println("Plugin class initialised");
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // 1. Class literal: the type is known when you write the code
        Class<String> fromLiteral = String.class;

        // 2. getClass(): the type is whatever the object really is at runtime
        Object value = "hello";
        Class<?> fromInstance = value.getClass();

        // 3. Class.forName(): the type is only known as a string at runtime
        Class<?> fromName = Class.forName("java.lang.String");

        System.out.println(fromLiteral == fromInstance); // one Class object per class
        System.out.println(fromInstance == fromName);

        // getClass() returns the runtime type, not the declared type
        List<String> list = new ArrayList<>();
        System.out.println(list.getClass().getName());

        // A class literal does not run static initialisers; forName does
        Class<?> lazy = Plugin.class;
        System.out.println("Got literal: " + lazy.getSimpleName());
        Class.forName("ClassObjects$Plugin");

        // Primitives and arrays have Class objects too
        System.out.println(int.class.getName());
        System.out.println(String[].class.getName());
        System.out.println(String[].class.getSimpleName());
        System.out.println(Plugin.class.getName());
        System.out.println(Plugin.class.getCanonicalName());
    }
}

Output:

Output
true
true
java.util.ArrayList
Got literal: Plugin
Plugin class initialised
int
[Ljava.lang.String;
String[]
ClassObjects$Plugin
ClassObjects.Plugin

Things to notice in the output:

  • list.getClass() reports ArrayList, not the declared type List: it always describes the real object.
  • The literal Plugin.class did not print anything; Class.forName loaded and initialised the class, so its static block ran. Use Class.forName(name, false, loader) to load without initialising.
  • Class.forName needs the binary name: nested classes use $ (ClassObjects$Plugin), and arrays have names like [Ljava.lang.String;. getCanonicalName() gives the name as you would write it in source.

Reading Class Information

A Class object describes the type itself: its name, package, modifiers, superclass and interfaces, and what kind of type it is (interface, enum, record, array, primitive).

Java
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.util.ArrayList;

public class ClassMetadata {

    record Point(int x, int y) { }

    public static void main(String[] args) {
        Class<?> cls = ArrayList.class;

        System.out.println("Name:        " + cls.getName());
        System.out.println("Package:     " + cls.getPackageName());
        System.out.println("Superclass:  " + cls.getSuperclass().getName());
        System.out.println("Modifiers:   " + Modifier.toString(cls.getModifiers()));

        System.out.print("Interfaces: ");
        for (Class<?> iface : cls.getInterfaces()) {
            System.out.print(" " + iface.getSimpleName());
        }
        System.out.println();

        // Ask what kind of type it is
        System.out.println("Interface?   " + cls.isInterface());
        System.out.println("Record?      " + Point.class.isRecord());

        // Records describe their components, in declaration order
        for (RecordComponent rc : Point.class.getRecordComponents()) {
            System.out.println("Component:   " + rc.getType() + " " + rc.getName());
        }

        // isAssignableFrom: can a value of the argument type be stored in this type?
        System.out.println(java.util.List.class.isAssignableFrom(ArrayList.class));
        System.out.println(ArrayList.class.isAssignableFrom(java.util.List.class));
    }
}

Output:

Output
Name:        java.util.ArrayList
Package:     java.util
Superclass:  java.util.AbstractList
Modifiers:   public
Interfaces:  List RandomAccess Cloneable Serializable
Interface?   false
Record?      true
Component:   int x
Component:   int y
true
false

getModifiers() returns the modifiers packed into an int; Modifier.toString turns it into text, and methods such as Modifier.isStatic test single flags. isAssignableFrom is the reflective version of instanceof for types: List can hold an ArrayList, but not the other way round.

Reading and Writing Fields

There are two families of lookup methods, and mixing them up is the most common reflection bug. The same split applies to methods and constructors.

MethodWhich membersInherited members?
getFields(), getField(name)public onlyyes, from superclasses and interfaces
getDeclaredFields(), getDeclaredField(name)all: public, protected, package-private, privateno, only this class

To find a private field declared in a superclass, call getDeclaredField on that superclass (frameworks walk up with getSuperclass() until they reach Object).

Java
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FieldAccess {

    static class Entity {
        public long id;
    }

    static class Person extends Entity {
        public String name;
        private int age;
        private static int created = 0;
        private final String country = "UK";
    }

    record Money(long amount) { }

    public static void main(String[] args) throws Exception {
        // getFields(): public fields only, including inherited ones
        System.out.print("getFields():        ");
        for (Field f : Person.class.getFields()) {
            System.out.print(f.getName() + " ");
        }
        System.out.println();

        // getDeclaredFields(): every field declared here, any access, none inherited
        System.out.print("getDeclaredFields(): ");
        for (Field f : Person.class.getDeclaredFields()) {
            System.out.print(f.getName() + " ");
        }
        System.out.println();

        Field age = Person.class.getDeclaredField("age");
        System.out.println(Modifier.toString(age.getModifiers()) + " " + age.getType());

        // Reading or writing a private field needs setAccessible(true) first
        Person p = new Person();
        age.setAccessible(true);
        age.setInt(p, 42);
        System.out.println("age = " + age.getInt(p));

        // Static fields belong to the class, so pass null instead of an object
        Field created = Person.class.getDeclaredField("created");
        created.setAccessible(true);
        created.set(null, 7);
        System.out.println("created = " + created.get(null));

        // A final instance field of a normal class can be changed once accessible...
        Field country = Person.class.getDeclaredField("country");
        country.setAccessible(true);
        country.set(p, "FR");
        System.out.println("country via reflection = " + country.get(p));

        // ...but a record's fields can never be written, even with setAccessible(true)
        Field amount = Money.class.getDeclaredField("amount");
        amount.setAccessible(true);
        try {
            amount.set(new Money(10), 99L);
        } catch (IllegalAccessException e) {
            System.out.println("Record field: IllegalAccessException");
        }
    }
}

Output:

Output
getFields():        name id 
getDeclaredFields(): name age created country 
private int
age = 42
created = 7
country via reflection = FR
Record field: IllegalAccessException

Step by step:

  • getFields() found the public name and the inherited public id; getDeclaredFields() found all four fields of Person but not id. The order of the returned array is not guaranteed.
  • Private fields need setAccessible(true) before get or set, otherwise you get IllegalAccessException.
  • Typed accessors such as getInt and setInt avoid boxing; get and set work with Object.
  • For a static field there is no object, so pass null.
Writing final fields through reflection is limited, and getting more so. A final instance field of an ordinary class can still be changed once accessible, as above, but since Java 26 this prints a warning, and a future release will refuse it (see How the JDK Has Tightened Reflection). A static final field, or any field of a record or hidden class, cannot be written at all: Field.set throws IllegalAccessException even after setAccessible(true), and a VarHandle for it is read-only. Lower-level tools can still overwrite them (sun.misc.Unsafe, JNI, bytecode instrumentation), but the result is unreliable. A compile-time constant such as static final String MODE = "prod" is copied by the compiler into every class that uses it, so those classes keep seeing the old value, and the JIT may also have treated the field as a constant. Treat final fields as final.

Calling Methods

A method is found by its name and its exact parameter types, because Java allows overloads. Then Method.invoke(target, args...) calls it.

Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodCalls {

    static class Calculator {
        public int add(int a, int b) {
            return a + b;
        }

        private int secret(int a) {
            return a * 1000;
        }

        public static int square(int n) {
            return n * n;
        }

        public int sum(int... values) {
            int total = 0;
            for (int v : values) total += v;
            return total;
        }

        public int divide(int a, int b) {
            return a / b;
        }
    }

    public static void main(String[] args) throws Exception {
        Calculator calc = new Calculator();
        Class<Calculator> cls = Calculator.class;

        // Look a method up by its name AND its exact parameter types
        Method add = cls.getMethod("add", int.class, int.class);
        Object result = add.invoke(calc, 3, 4); // arguments and result are boxed
        System.out.println("add: " + result);

        // int.class and Integer.class are different parameter types
        try {
            cls.getMethod("add", Integer.class, Integer.class);
        } catch (NoSuchMethodException e) {
            System.out.println("No add(Integer, Integer): NoSuchMethodException");
        }

        // Private methods: getDeclaredMethod plus setAccessible
        Method secret = cls.getDeclaredMethod("secret", int.class);
        secret.setAccessible(true);
        System.out.println("secret: " + secret.invoke(calc, 5));

        // Static methods: the target object is null
        Method square = cls.getMethod("square", int.class);
        System.out.println("square: " + square.invoke(null, 9));

        // Varargs: the parameter type is int[], so pass an int[]
        Method sum = cls.getMethod("sum", int[].class);
        System.out.println("sum: " + sum.invoke(calc, (Object) new int[] {1, 2, 3}));

        // Wrong argument types are rejected before the method runs
        try {
            add.invoke(calc, "3", "4");
        } catch (IllegalArgumentException e) {
            System.out.println("Bad arguments: IllegalArgumentException");
        }

        // An exception thrown INSIDE the method arrives wrapped
        Method divide = cls.getMethod("divide", int.class, int.class);
        try {
            divide.invoke(calc, 1, 0);
        } catch (InvocationTargetException e) {
            System.out.println("Wrapped: " + e.getCause());
        }
    }
}

Output:

Output
add: 7
No add(Integer, Integer): NoSuchMethodException
secret: 5000
square: 81
sum: 6
Bad arguments: IllegalArgumentException
Wrapped: java.lang.ArithmeticException: / by zero

The rules this program shows:

  • Parameter types must match exactly. int.class and Integer.class are different, so looking up add(Integer, Integer) fails.
  • Arguments and results are boxed. invoke takes Object... and returns Object, so 3 becomes an Integer and is unboxed again for the call. A void method returns null.
  • Static methods take null as the target.
  • Varargs are just arrays. sum(int...) is looked up with int[].class and called with an int[]. The (Object) cast stops Java from spreading an Object[] array across the parameters.
  • Two different failures: wrong argument types throw IllegalArgumentException before the method runs; an exception thrown inside the method arrives wrapped in InvocationTargetException. Always look at getCause() to see the real error.

getMethods() includes public methods inherited from superclasses and interfaces (so you will see toString, hashCode and the rest from Object); getDeclaredMethods() lists only this class's own methods, of any access level.

Creating Objects

Constructors work like methods: look one up by its parameter types with getDeclaredConstructor, then call newInstance(args...). This is also how plugins are loaded: the class name comes from configuration, and after one reflective call the rest of the code uses an ordinary interface.

Java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class CreatingObjects {

    public interface Greeter {
        String greet(String name);
    }

    public static class EnglishGreeter implements Greeter {
        public String greet(String name) {
            return "Hello, " + name;
        }
    }

    static class Server {
        private final String host;
        private final int port;

        Server() {
            this("localhost", 8080);
        }

        Server(String host, int port) {
            if (port <= 0) throw new IllegalArgumentException("bad port " + port);
            this.host = host;
            this.port = port;
        }

        @Override
        public String toString() {
            return host + ":" + port;
        }
    }

    public static void main(String[] args) throws Exception {
        // Pick a constructor by its parameter types, then call newInstance
        Constructor<Server> noArgs = Server.class.getDeclaredConstructor();
        System.out.println(noArgs.newInstance());

        Constructor<Server> twoArgs =
                Server.class.getDeclaredConstructor(String.class, int.class);
        System.out.println(twoArgs.newInstance("db.internal", 5432));

        // Exceptions thrown by the constructor arrive wrapped, as with methods
        try {
            twoArgs.newInstance("db.internal", -1);
        } catch (InvocationTargetException e) {
            System.out.println("Wrapped: " + e.getCause().getMessage());
        }

        // The class name can come from a config file: this is how plugins are loaded
        String configured = "CreatingObjects$EnglishGreeter";
        Class<? extends Greeter> type =
                Class.forName(configured).asSubclass(Greeter.class);
        Greeter greeter = type.getDeclaredConstructor().newInstance();
        System.out.println(greeter.greet("Ada")); // from here on, no reflection is needed
    }
}

Output:

Output
localhost:8080
db.internal:5432
Wrapped: bad port -1
Hello, Ada

asSubclass(Greeter.class) checks that the loaded class really implements Greeter and gives you a correctly typed Class, so no unchecked cast is needed.

Do not use Class.newInstance(). It has been deprecated since Java 9 because it passes any checked exception from the constructor straight to the caller, even though newInstance() does not declare it. getDeclaredConstructor().newInstance() wraps such exceptions in InvocationTargetException instead.

Reading Annotations

Annotations are how frameworks know what to do with your code: @Test, @Entity, @JsonProperty. At runtime they are read with getAnnotation and isAnnotationPresent, available on classes, fields, methods, constructors and parameters.

The program below is a miniature test runner. It finds every method marked @Check, calls it, and reports a pass or a failure.

Java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;

public class AnnotationRunner {

    // RUNTIME retention is what makes the annotation visible to reflection
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface Check {
        String value() default "";
    }

    // CLASS retention (the default) is kept in the .class file but hidden at runtime
    @Target(ElementType.METHOD)
    @interface Invisible { }

    public static class OrderChecks {
        @Check("total is never negative")
        public void totalIsPositive() { }

        @Check("discount is capped at 50%")
        public void discountIsCapped() {
            throw new IllegalStateException("discount was 60%");
        }

        @Invisible
        public void notACheck() { }

        public void helper() { }
    }

    public static void main(String[] args) throws Exception {
        Class<OrderChecks> cls = OrderChecks.class;
        Object target = cls.getDeclaredConstructor().newInstance();

        Method[] methods = cls.getDeclaredMethods();
        // getDeclaredMethods() returns methods in no particular order, so sort them
        Arrays.sort(methods, Comparator.comparing(Method::getName));

        for (Method m : methods) {
            Check check = m.getAnnotation(Check.class);
            if (check == null) {
                int visible = m.getAnnotations().length;
                System.out.println("skip  " + m.getName() + " (annotations seen: " + visible + ")");
                continue;
            }
            try {
                m.invoke(target);
                System.out.println("PASS  " + check.value());
            } catch (InvocationTargetException e) {
                String reason = e.getCause().getMessage();
                System.out.println("FAIL  " + check.value() + ": " + reason);
            }
        }
    }
}

Output:

Output
FAIL  discount is capped at 50%: discount was 60%
skip  helper (annotations seen: 0)
skip  notACheck (annotations seen: 0)
PASS  total is never negative

Notice that notACheck reports 0 annotations, even though @Invisible is written on it. An annotation is visible to reflection only if it is declared with @Retention(RetentionPolicy.RUNTIME). The default retention, CLASS, keeps the annotation in the .class file but the JVM does not expose it. Forgetting RUNTIME is the usual reason a custom annotation "does nothing". More on this in Java Annotations.

Generic Type Information

Because of type erasure, an object does not know its own type arguments: a new ArrayList<String>() is just an ArrayList at runtime. But declarations keep them. A field, method parameter or return type declared as List<String> records String in the class file, and reflection can read it.

Java
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GenericTypes {

    static class Order {
        List<String> tags;
        Map<String, Integer> quantities;
    }

    public static void main(String[] args) throws Exception {
        Field tags = Order.class.getDeclaredField("tags");

        // getType() gives the erased type only
        System.out.println("getType():         " + tags.getType().getName());

        // getGenericType() keeps the type arguments written in the source
        Type generic = tags.getGenericType();
        if (generic instanceof ParameterizedType pt) {
            System.out.println("raw type:          " + pt.getRawType().getTypeName());
            Type argument = pt.getActualTypeArguments()[0];
            System.out.println("type argument:     " + argument.getTypeName());
        }

        Field quantities = Order.class.getDeclaredField("quantities");
        ParameterizedType mapType = (ParameterizedType) quantities.getGenericType();
        for (Type arg : mapType.getActualTypeArguments()) {
            System.out.println("map type argument: " + arg.getTypeName());
        }

        // An object does not remember its type arguments: they were erased
        List<String> local = new ArrayList<>();
        System.out.println("runtime class:     " + local.getClass().getName());
    }
}

Output:

Output
getType():         java.util.List
raw type:          java.util.List
type argument:     java.lang.String
map type argument: java.lang.String
map type argument: java.lang.Integer
runtime class:     java.util.ArrayList

getType() returns the erased class, List. getGenericType() returns a Type; when it is a ParameterizedType, getActualTypeArguments() gives the arguments. This is how Jackson knows that a List<Order> field should be filled with Order objects. The matching methods for methods are getGenericReturnType() and getGenericParameterTypes().

The Exceptions You Will Meet

Most reflective calls throw checked exceptions. Since Java 7 they share one parent, ReflectiveOperationException, so one catch or throws clause can cover them all.

ExceptionThrown whenChecked?
ClassNotFoundExceptionClass.forName cannot find the class nameyes
NoSuchFieldException, NoSuchMethodExceptionno member with that name and those parameter typesyes
IllegalAccessExceptionthe member is not accessible, or a final field cannot be writtenyes
InstantiationExceptiontrying to create an instance of an abstract class or interfaceyes
InvocationTargetExceptionthe called method or constructor threw; the original is in getCause()yes
IllegalArgumentExceptionwrong number or types of arguments, or a target object of the wrong classno
InaccessibleObjectExceptionsetAccessible(true) refused by the module system (Java 9+)no

Reflection and the Module System

Since Java 9, a module decides which of its packages other code may reflect into. Public members of exported packages are always reachable, but setAccessible(true) on private members needs the package to be opened. Since Java 16 the JDK enforces this for its own internals (JEP 396), and since Java 17 the old command-line escape hatch, --illegal-access, is gone (JEP 403).

Java
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;

public class ModuleAccess {

    static class Account {
        private double balance = 100.0;
    }

    public static void main(String[] args) throws Exception {
        // Your own classes: setAccessible works
        Field balance = Account.class.getDeclaredField("balance");
        System.out.println("own class:     " + balance.trySetAccessible());

        // JDK internals: java.base does not open java.lang to your code
        Field value = String.class.getDeclaredField("value");
        System.out.println("String.value:  " + value.trySetAccessible());

        try {
            value.setAccessible(true);
        } catch (InaccessibleObjectException e) {
            System.out.println("setAccessible: InaccessibleObjectException");
        }
    }
}

Output:

Output
own class:     true
String.value:  false
setAccessible: InaccessibleObjectException

trySetAccessible() returns false instead of throwing, which is handy when you want to fall back to another approach. Your own classes, on the class path, are in the unnamed module, which is open to everyone, so reflection on them just works.

When a framework needs private access to your classes and you do use modules, open the package to it in module-info.java:

Java
module com.example.shop {
    requires com.fasterxml.jackson.databind;

    // Let Jackson read and write private fields in this package
    opens com.example.shop.model to com.fasterxml.jackson.databind;
}

For code you cannot change, the JVM option --add-opens java.base/java.lang=ALL-UNNAMED opens a package at launch. Treat it as a temporary workaround, not a design.

How the JDK Has Tightened Reflection

Reflection used to be a way around every rule in the language. Each recent Java release has closed part of that gap, and the direction is clear: reflection on your own classes keeps working, while reaching into other modules' private state or changing final fields is being phased out.

JavaChangeWhat it means for your code
9Module systemsetAccessible(true) on private members only works if the package is opened to you; illegal access to JDK internals prints a warning
12Reflection hides the internal fields of Field itselfthe old trick of clearing the FINAL flag through Field.modifiers stops working
16JDK internals strongly encapsulated by default (JEP 396)reflecting into java.* private members fails instead of warning
17--illegal-access removed (JEP 403)the only remaining switch is a targeted --add-opens
18Core reflection reimplemented on method handles (JEP 416)no change in what is allowed. -Djdk.reflect.useDirectMethodHandle=false switched back to the old implementation as a compatibility fallback; it never granted extra access
22Old implementation removedthe jdk.reflect.useDirectMethodHandle property no longer has any effect
23Memory-access methods of sun.misc.Unsafe deprecated for removal (JEP 471)the usual escape hatch for writing static final fields is on its way out
24Warning on first use of those Unsafe methods (JEP 498)libraries that still use them now show up in your logs
26Changing a final field through reflection prints a warning (JEP 500)--illegal-final-field-mutation=deny makes it throw IllegalAccessException; that is planned to become the default

What to do about it:

  • Test with the future default today. Run your tests with --illegal-final-field-mutation=deny on Java 26, or with debug to get a stack trace for every mutation, and find out which libraries still change final fields.
  • Upgrade before you add flags. When a warning names a library, check its release notes first: a newer version often no longer needs the access. Command-line options such as --add-opens or --enable-final-field-mutation are a temporary bridge for code you cannot change yet.
  • Design for it. Give frameworks a constructor or a record to work with instead of letting them write private or final fields, and use opens ... to ... in module-info.java for exactly the packages that need it.

Performance

A reflective call does more work than a direct one:

  • Looking members up with getMethod or getDeclaredField searches the class and returns a fresh copy each time. This is the expensive part.
  • Each call checks access, boxes primitive arguments into an Object[], and unboxes the result.
  • The JIT compiler sees less: it cannot inline through a Method it does not know is constant.

The practical rules are short. Look members up once and keep them (frameworks build these caches when they start), and call setAccessible(true) once rather than before every call. For a call on a hot path, a MethodHandle stored in a static final field is the fastest reflective option, because the JIT can treat it as a constant and inline the target. Since Java 18, Method.invoke is itself implemented with method handles (JEP 416).

Java
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;

public class CachedReflection {

    public static class Product {
        public String getName() {
            return "keyboard";
        }
    }

    // Look the method up once and reuse it: the lookup is the expensive part
    private static final Method GET_NAME;
    private static final MethodHandle GET_NAME_HANDLE;

    static {
        try {
            GET_NAME = Product.class.getMethod("getName");
            GET_NAME_HANDLE = MethodHandles.lookup().findVirtual(
                    Product.class, "getName", MethodType.methodType(String.class));
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void main(String[] args) throws Throwable {
        Product product = new Product();

        String viaMethod = (String) GET_NAME.invoke(product);
        String viaHandle = (String) GET_NAME_HANDLE.invoke(product);

        System.out.println(viaMethod + " / " + viaHandle);
    }
}

Output:

Output
keyboard / keyboard

If you need numbers for your own case, measure with a benchmark harness such as JMH; timings from a simple loop are dominated by JIT warm-up and are misleading.

Putting It Together: A Tiny Dependency Injector

This is a stripped-down version of what Spring or Guice do. Ask the container for an OrderService, and it:

  • finds the constructor marked @Inject (or the no-arg one);
  • reads the constructor's parameter types: Repository and Clock;
  • builds each of those the same way, recursively;
  • calls the constructor with them and remembers the result, so every request gets the same instance.
Java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

public class TinyInjector {

    @Retention(RetentionPolicy.RUNTIME)
    @interface Inject { }

    // --- application classes: no reflection in here ---
    public static class Clock {
        public String now() {
            return "09:30";
        }
    }

    public static class Repository {
        public String find(int id) {
            return "order-" + id;
        }
    }

    public static class OrderService {
        private final Repository repository;
        private final Clock clock;

        @Inject
        public OrderService(Repository repository, Clock clock) {
            this.repository = repository;
            this.clock = clock;
        }

        public String describe(int id) {
            return repository.find(id) + " checked at " + clock.now();
        }
    }

    // --- the container: all the reflection lives here ---
    private final Map<Class<?>, Object> singletons = new HashMap<>();

    public <T> T get(Class<T> type) throws ReflectiveOperationException {
        Object existing = singletons.get(type);
        if (existing != null) return type.cast(existing);

        Constructor<?> constructor = pickConstructor(type);
        Class<?>[] paramTypes = constructor.getParameterTypes();
        Object[] dependencies = new Object[paramTypes.length];
        for (int i = 0; i < paramTypes.length; i++) {
            dependencies[i] = get(paramTypes[i]); // build each dependency first
        }
        T instance = type.cast(constructor.newInstance(dependencies));
        singletons.put(type, instance);
        System.out.println("created " + type.getSimpleName());
        return instance;
    }

    // Use the @Inject constructor if there is one, otherwise the no-arg constructor
    private static Constructor<?> pickConstructor(Class<?> type)
            throws NoSuchMethodException {
        for (Constructor<?> c : type.getConstructors()) {
            if (c.isAnnotationPresent(Inject.class)) return c;
        }
        return type.getConstructor();
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        TinyInjector container = new TinyInjector();
        OrderService service = container.get(OrderService.class);
        System.out.println(service.describe(42));
        System.out.println(container.get(OrderService.class) == service); // same instance
    }
}

Output:

Output
created Repository
created Clock
created OrderService
order-42 checked at 09:30
true

The dependencies are created first (Repository, then Clock), then OrderService, and the second request returns the cached instance. Note where the reflection lives: entirely inside the container. OrderService is plain Java that you could also build by hand in a unit test. That separation is the right shape for any code that uses reflection. A real container adds what this one leaves out: interfaces bound to implementations, scopes, and detection of circular dependencies (here, two classes that need each other would recurse forever).

Three Lesser-Known Facts

Three behaviours that regularly surprise people, all shown by one program:

  • Parameter names are usually gone. By default the compiler does not store them, so reflection reports arg0, arg1, and so on. Compile with javac -parameters to keep them. Spring and Jackson rely on this flag to match constructor arguments by name; Spring Boot's Maven and Gradle plugins turn it on for you.
  • Enums cannot be created through reflection. Constructor.newInstance refuses outright, even after setAccessible(true). This is why an enum with a single constant is the safest way to write a singleton: reflection cannot make a second one.
  • Arrays of a runtime type are created with java.lang.reflect.Array, since new T[3] is not allowed for a type variable T. Array.get and Array.set work on any array, including primitive ones.
Java
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class LesserKnown {

    enum Singleton {
        INSTANCE
    }

    static class Transfer {
        public void send(String fromAccount, String toAccount, long amountInCents) {
        }
    }

    public static void main(String[] args) throws Exception {
        // 1. Parameter names: real names only if compiled with -parameters
        Method send =
                Transfer.class.getMethod("send", String.class, String.class, long.class);
        for (Parameter p : send.getParameters()) {
            System.out.print(p.getName() + " ");
        }
        boolean present = send.getParameters()[0].isNamePresent();
        System.out.println("(names present: " + present + ")");

        // 2. Enums cannot be created through reflection
        Constructor<?> c = Singleton.class.getDeclaredConstructors()[0];
        c.setAccessible(true);
        try {
            c.newInstance("SECOND", 1);
        } catch (IllegalArgumentException e) {
            System.out.println("enum: " + e.getMessage());
        }

        // 3. Arrays of a type known only at runtime
        Class<?> elementType = Class.forName("java.lang.String");
        Object array = Array.newInstance(elementType, 3);
        Array.set(array, 0, "first");
        System.out.println(array.getClass().getSimpleName() + " of length "
                + Array.getLength(array) + ", [0] = " + Array.get(array, 0));
    }
}

Output when compiled with plain javac:

Output
arg0 arg1 arg2 (names present: false)
enum: Cannot reflectively create enum objects
String[] of length 3, [0] = first

Output when compiled with javac -parameters:

Output
fromAccount toAccount amountInCents (names present: true)
enum: Cannot reflectively create enum objects
String[] of length 3, [0] = first

When Not to Use Reflection

Reflection is the right tool for framework and infrastructure code that must work with types it has never seen. In ordinary application code there is almost always a better option:

Instead of reflecting to…Prefer
call one of several known methods by namea Map<String, Runnable> or a switch over the names
pass behaviour aroundan interface or a lambda
load optional implementationsjava.util.ServiceLoader with an interface
read a private field in a testtest through the public API, or make the field package-private
wrap calls with logging or timinga decorator class, or a dynamic proxy if it must be generic
generate repetitive code such as mappersan annotation processor, which does the work at compile time

Each of these keeps the compiler checking your code, keeps working under the module system, and stays visible to refactoring tools. Reflection gives all three up, so use it where nothing else can do the job, keep it in one place, and cache what it looks up.