CKTIS / Java
Java reflection: accessing fields and methods
In Java SE 21, `Field` and `Method` let you inspect metadata and annotations, change field values, and invoke methods. Finding a private member does not grant access, and `setAccessible(true)` is subject to module rules.
Version: Java SE 21
Syntax
Java SE 21 — java.lang.reflect
Field f = Owner.class.getDeclaredField("count");
Method m = Owner.class.getDeclaredMethod("add", int.class);
f.setAccessible(true);
m.setAccessible(true);
// Field instance methods
void setAccessible(boolean flag)
void set(Object receiver, Object value)
Object get(Object receiver)
String getName()
Class<?> getType()
void setInt(Object receiver, int value)
int getInt(Object receiver)
<T extends Annotation> T getAnnotation(Class<T> annotationType)
// Method instance methods
void setAccessible(boolean flag)
Object invoke(Object receiver, Object... args) throws IllegalAccessException, InvocationTargetException
boolean isAnnotationPresent(Class<? extends Annotation> annotationType)
String getName()Field and Method in java.lang.reflect represent class members. getDeclaredField(name) looks up the exact field name; getDeclaredMethod(name, parameterTypes...) selects a method by its exact name and declared parameter types in order. int.class and Integer.class select different overloads. The JVM allows methods in the same class to have identical names and parameter types but different return types. If one matching method's return type is more specific than all the others, getDeclaredMethod selects that method; otherwise it selects one of the matches arbitrarily. Both lookups include private but not inherited members and report a missing match with NoSuchFieldException or NoSuchMethodException, respectively. Lookup does not grant access.
On a Field or Method, a successful setAccessible(true) suppresses Java language access checks for that reflection object; it does not change the member's modifier. setAccessible(false) restores checks. For a private member, suppression is allowed within the same module; across modules the declaring package must be open to the caller's module (opens), not merely exported (exports). If the module prevents suppression, setAccessible(true) throws InaccessibleObjectException, while trySetAccessible() returns false. If an installed security manager denies the request, either method can throw SecurityException.
Field.getName() gives the simple field name and getType() gives its declared type as a Class<?>, such as int.class. get(receiver) boxes a primitive value; set(receiver, value) unboxes a compatible value for a primitive field. getInt(receiver) returns an int from an int field or a primitive field that can widen to int. setInt(receiver, value) writes an int to an int field or to a wider primitive type. These operations do not narrow values. Suppression does not permit writes to static final fields or to final fields in records or hidden classes.
Method.getName() gives the simple method name. invoke(receiver, args...) calls the method already selected: it unboxes primitive arguments as needed and can widen them. It boxes a primitive result and returns null for void. For reads, writes, and calls, supply a compatible instance; for a static member the receiver is ignored and may be null. A null receiver for an instance member causes NullPointerException; an incompatible receiver, value, or argument list causes IllegalArgumentException. An access denial at the point of use gives IllegalAccessException. An exception thrown by the target method is wrapped in InvocationTargetException; inspect it with getCause().
Field.getAnnotation(Label.class) returns the field's declaration annotation or null. Method.isAnnotationPresent(Label.class) tests for the method's declaration annotation without returning it. Define the annotation type with @Retention(RetentionPolicy.RUNTIME) so reflection can see it. These metadata queries do not require suppressing access checks.
Examples
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
final class Owner {
@Label("items")
private int count = 1;
@Label("operation")
private int add(int delta) {
return count + delta;
}
}
public class ReflectionMembersDemo {
public static void main(String[] args) throws ReflectiveOperationException {
Owner owner = new Owner();
Field field = Owner.class.getDeclaredField("count");
Method method = Owner.class.getDeclaredMethod("add", int.class);
try {
field.get(owner);
throw new AssertionError("Private field was readable before override");
} catch (IllegalAccessException expected) {
System.out.println("field access denied");
}
try {
method.invoke(owner, 5);
throw new AssertionError("Private method was callable before override");
} catch (IllegalAccessException expected) {
System.out.println("method access denied");
}
field.setAccessible(true);
method.setAccessible(true);
System.out.println(field.getName() + ":" + field.getType().getName()
+ " label=" + field.getAnnotation(Label.class).value());
field.set(owner, Integer.valueOf(7));
System.out.println("get=" + field.get(owner));
field.setInt(owner, 11);
System.out.println("getInt=" + field.getInt(owner));
System.out.println(method.getName() + " annotated="
+ method.isAnnotationPresent(Label.class));
System.out.println("invoke=" + method.invoke(owner, 5));
}
}Result
field access denied method access denied count:int label=items get=7 getInt=11 add annotated=true invoke=16
`Owner` and `ReflectionMembersDemo` are separate top-level classes in the same module. The first read and call are denied. After suppressing the checks, the example writes `7` and `11`, and `add(5)` returns `16` without changing `count`.
Related lessons
- Java · Lesson 54 · Advanced · Version: 2