Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Reflective field access in Java

Identify an annotated field, read its declared type, and assign a constructed dependency while respecting Java SE 21 access rules.

Version: Java SE 21

Syntax

java.lang.reflect.Field — instance methods in Java SE 21
Class<?> getType()
boolean isAnnotationPresent(Class<? extends java.lang.annotation.Annotation> annotationClass)
void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException
void setAccessible(boolean flag)

A java.lang.reflect.Field describes a field, not its value on a particular object. Class.getDeclaredFields() finds fields declared by that class, including private fields but not inherited ones. Field.isAnnotationPresent(Inject.class) returns true when the @Inject declaration annotation is present on the field; a custom annotation needs @Retention(RetentionPolicy.RUNTIME) to be visible to reflection. Reading this metadata does not require suppressing access checks.

Field.getType() returns the declared type as a Class<?>, not the type of the current value. For List<String> it returns List.class; for int it returns int.class. Use getGenericType() to examine declared generic arguments. In field injection, use the type to decide what to build, finish constructing that dependency recursively, and then assign it.

Field.setAccessible(true) suppresses Java language access checks for that Field object when permitted; false restores the checks. It does not change the field's modifiers. To access a private field from another module this way, the package must be open to the caller's module; exports alone is not enough. If checks cannot be suppressed, the method throws InaccessibleObjectException; trySetAccessible() returns false in that case. Both methods can throw SecurityException if an active security manager denies permission.

Field.set(obj, value) writes the value. For an instance field, obj must be a compatible instance: null throws NullPointerException, and a wrong receiver type throws IllegalArgumentException. For a static field, obj is ignored and may be null. The value must be compatible with the field type; for a primitive field, the method unboxes the value and allows widening, not narrowing. An incompatible value throws IllegalArgumentException.

IllegalAccessException is a checked exception thrown by the write when access is denied or a final field is not writable. Suppressing checks still does not let you write static final fields or final fields in records or hidden classes. Avoid writing final fields; prefer constructor injection when you control the class.

Examples

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws ReflectiveOperationException {
        System.out.println(build(Service.class).message());
    }

    private static <T> T build(Class<T> type) throws ReflectiveOperationException {
        T instance = type.getDeclaredConstructor().newInstance();
        for (Field field : type.getDeclaredFields()) {
            if (!field.isAnnotationPresent(Inject.class)) {
                continue;
            }
            Object dependency = build(field.getType());
            field.setAccessible(true);
            field.set(instance, dependency);
        }
        return instance;
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Inject {}

class Service {
    @Inject
    private Repository repository;

    String message() {
        return repository.message();
    }
}

class Repository {
    String message() {
        return "ready";
    }
}

Result

ready

`build` creates `Service`, detects `@Inject`, and recursively creates `Repository` before writing the private `repository` field. The expected output is `ready`. The example deliberately uses concrete classes with accessible no-argument constructors; it does not handle cycles or select implementations for interfaces.

Related lessons

  • Java · Lesson 59 · Advanced · Version: 2

Sources