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 Getting a Class Object Reading Class Information Reading and Writing Fields Calling Methods Creating Objects Reading Annotations Generic Type Information The Exceptions You Will Meet Reflection and the Module System How the JDK Has Tightened Reflection Performance Putting It Together: A Tiny Dependency Injector Three Lesser-Known Facts When Not to Use Reflection
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()
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.
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:
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()StringNoSuchMethodExceptionidtotal
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
and calls them.@Test - Spring creates beans through their constructors and fills
dependencies.@Autowired - 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
Getting a Class Object
Every reflective operation starts from a Class
| How | Use it when | Runs static initialisers? |
|---|---|---|
String.class | you know the type while writing the code | no |
obj.getClass() | you have an object and want its real (runtime) type | already ran when the object was created |
Class.forName("java.lang.String") | the class name is only known at runtime, for example from a config file | yes |
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:
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:
reportslist.getClass() , not the declared typeArrayList : it always describes the real object.List- The literal
did not print anything;Plugin.class loaded and initialised the class, so its static block ran. UseClass.forName to load without initialising.Class.forName(name, false, loader) needs the binary name: nested classes useClass.forName ($ ), and arrays have names likeClassObjects$Plugin .[Ljava.lang.String; gives the name as you would write it in source.getCanonicalName()
Reading Class Information
A Class
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:
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()intModifier.toStringModifier.isStaticisAssignableFrominstanceofListArrayList
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.
| Method | Which members | Inherited members? |
|---|---|---|
getFields()getField(name) | public only | yes, from superclasses and interfaces |
getDeclaredFields()getDeclaredField(name) | all: public, protected, package-private, private | no, only this class |
To find a private field declared in a superclass, call getDeclaredFieldgetSuperclass()Object
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:
getFields(): name id
getDeclaredFields(): name age created country
private int
age = 42
created = 7
country via reflection = FR
Record field: IllegalAccessException
Step by step:
found the publicgetFields() and the inherited publicname ;id found all four fields ofgetDeclaredFields() but notPerson . The order of the returned array is not guaranteed.id- Private fields need
beforesetAccessible(true) orget , otherwise you getset .IllegalAccessException - Typed accessors such as
andgetInt avoid boxing;setInt andget work withset .Object - For a
field there is no object, so passstatic .null
finalstatic finalField.setIllegalAccessExceptionsetAccessible(true)VarHandlesun.misc.Unsafestatic final String MODE = "prod"Calling Methods
A method is found by its name and its exact parameter types, because Java allows overloads. Then Method.invoke(target, args...)
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:
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.
andint.class are different, so looking upInteger.class fails.add(Integer, Integer) - Arguments and results are boxed.
takesinvoke and returnsObject... , soObject becomes an3 and is unboxed again for the call. AInteger method returnsvoid .null - Static methods take
as the target.null - Varargs are just arrays.
is looked up withsum(int...) and called with anint[].class . Theint[] cast stops Java from spreading an(Object) array across the parameters.Object[] - Two different failures: wrong argument types throw
before the method runs; an exception thrown inside the method arrives wrapped inIllegalArgumentException . Always look atInvocationTargetException to see the real error.getCause()
getMethods()toStringhashCodeObjectgetDeclaredMethods()
Creating Objects
Constructors work like methods: look one up by its parameter types with getDeclaredConstructornewInstance(args...)
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:
localhost:8080
db.internal:5432
Wrapped: bad port -1
Hello, Ada
asSubclass(Greeter.class)GreeterClass
Class.newInstance()newInstance()getDeclaredConstructor().newInstance()InvocationTargetExceptionReading Annotations
Annotations are how frameworks know what to do with your code: @Test@Entity@JsonPropertygetAnnotationisAnnotationPresent
The program below is a miniature test runner. It finds every method marked @Check
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:
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@Invisible@Retention(RetentionPolicy.RUNTIME)CLASS.classRUNTIME
Generic Type Information
Because of new ArrayList<String>()ArrayListList<String>String
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:
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()ListgetGenericType()TypeParameterizedTypegetActualTypeArguments()List<Order>OrdergetGenericReturnType()getGenericParameterTypes()
The Exceptions You Will Meet
Most reflective calls throw checked exceptions. Since Java 7 they share one parent, ReflectiveOperationExceptioncatchthrows
| Exception | Thrown when | Checked? |
|---|---|---|
ClassNotFoundException | Class.forName | yes |
NoSuchFieldExceptionNoSuchMethodException | no member with that name and those parameter types | yes |
IllegalAccessException | the member is not accessible, or a final field cannot be written | yes |
InstantiationException | trying to create an instance of an abstract class or interface | yes |
InvocationTargetException | the called method or constructor threw; the original is in getCause() | yes |
IllegalArgumentException | wrong number or types of arguments, or a target object of the wrong class | no |
InaccessibleObjectException | setAccessible(true) | 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)--illegal-access
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:
own class: true
String.value: false
setAccessible: InaccessibleObjectException
trySetAccessible()false
When a framework needs private access to your classes and you do use modules, open the package to it in module-info.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
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
| Java | Change | What it means for your code |
|---|---|---|
| 9 | Module system | setAccessible(true) |
| 12 | Reflection hides the internal fields of Field | the old trick of clearing the FINALField.modifiers |
| 16 | JDK internals strongly encapsulated by default ( | reflecting into java.* |
| 17 | --illegal-access | the only remaining switch is a targeted --add-opens |
| 18 | Core reflection reimplemented on method handles ( | no change in what is allowed. -Djdk.reflect.useDirectMethodHandle=false |
| 22 | Old implementation removed | the jdk.reflect.useDirectMethodHandle |
| 23 | Memory-access methods of sun.misc.Unsafe | the usual escape hatch for writing static final |
| 24 | Warning on first use of those Unsafe | libraries that still use them now show up in your logs |
| 26 | Changing a final | --illegal-final-field-mutation=denyIllegalAccessException |
What to do about it:
- Test with the future default today. Run your tests with
on Java 26, or with--illegal-final-field-mutation=deny to get a stack trace for every mutation, and find out which libraries still changedebug fields.final - 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
or--add-opens are a temporary bridge for code you cannot change yet.--enable-final-field-mutation - Design for it. Give frameworks a constructor or a record to work with instead of letting them write private or final fields, and use
inopens ... to ... for exactly the packages that need it.module-info.java
Performance
A reflective call does more work than a direct one:
- Looking members up with
orgetMethod searches the class and returns a fresh copy each time. This is the expensive part.getDeclaredField - Each call checks access, boxes primitive arguments into an
, and unboxes the result.Object[] - The JIT compiler sees less: it cannot inline through a
it does not know is constant.Method
The practical rules are short. Look members up once and keep them (frameworks build these caches when they start), and call setAccessible(true)static finalMethod.invoke
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:
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
- finds the constructor marked
(or the no-arg one);@Inject - reads the constructor's parameter types:
andRepository ;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.
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:
created Repository
created Clock
created OrderService
order-42 checked at 09:30
true
The dependencies are created first (RepositoryClockOrderServiceOrderService
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 , and so on. Compile witharg1 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.javac -parameters - Enums cannot be created through reflection.
refuses outright, even afterConstructor.newInstance . This is why an enum with a single constant is the safest way to write a singleton: reflection cannot make a second one.setAccessible(true) - Arrays of a runtime type are created with
, sincejava.lang.reflect.Array is not allowed for a type variablenew T[3] .T andArray.get work on any array, including primitive ones.Array.set
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
arg0 arg1 arg2 (names present: false)
enum: Cannot reflectively create enum objects
String[] of length 3, [0] = first
Output when compiled with javac -parameters
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 name | a Map<String, Runnable>switch |
| pass behaviour around | an interface or a lambda |
| load optional implementations | java.util.ServiceLoader |
| read a private field in a test | test through the public API, or make the field package-private |
| wrap calls with logging or timing | a decorator class, or a |
| generate repetitive code such as mappers | an 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.