Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Class reflection: names, fields, constructors, and annotations

Inspect an object's actual class in Java SE 21, read its name, find declared fields and constructors, and distinguish direct annotations from inherited ones.

Version: Java SE 21

Syntax

static void inspect(Base value) throws NoSuchMethodException {
    Class<Item> type = Item.class;
    Class<?> runtimeType = value.getClass();
    String name = type.getName();
    Field[] fields = type.getDeclaredFields();
    java.lang.reflect.Constructor<?>[] constructors = type.getDeclaredConstructors();
    java.lang.reflect.Constructor<Item> constructor = type.getDeclaredConstructor(int.class);
    boolean audited = type.isAnnotationPresent(Audited.class);
}

Use a class literal such as Item.class when the type is known. A type variable such as T cannot be used in a class literal. Call Object.getClass() on an object to get its actual runtime class, regardless of the variable's declared type. Class.getName() returns the binary name of a non-hidden class or interface (for example, Main$Item). A hidden type has / followed by a suffix in its name, an array has an encoded name such as [I, and a primitive type or void uses its keyword.

Class.getDeclaredFields() returns a Field[] of fields declared by that class or interface, regardless of access level, excluding inherited fields. getFields() returns only public fields, including inherited ones. Neither array has a guaranteed order.

Class.getDeclaredConstructors() returns a Constructor<?>[] of all constructors declared by the class, including private and implicitly declared constructors, in no guaranteed order. Constructors are not inherited. getConstructors() returns only public constructors. Both return an empty array for an interface, array type, primitive type, or void.

Class.getDeclaredConstructor(...) returns one Constructor<T>. Supply the exact formal parameter types in declaration order: int.class is not Integer.class, and no arguments means a no-argument constructor. For an inner class declared in a non-static context, supply the enclosing instance's type first. No match means NoSuchMethodException. Finding a member does not grant permission to access a field or invoke a constructor; module boundaries can prevent suppressing access checks.

Class.isAnnotationPresent(A.class) tests whether the declaration annotation A is visible at runtime (RetentionPolicy.RUNTIME) and present directly or, if A has @Inherited, through the superclass chain, not through interfaces. For direct presence only, use getDeclaredAnnotation(A.class) != null. To read repeatable annotations stored in a container, use getAnnotationsByType(A.class).

Examples

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class Main {
    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @interface Audited {}

    @Audited
    static class Base {
        public int inheritedId;
    }

    static final class Item extends Base {
        private final int size;
        public String label = "item";

        public Item() { this(0); }
        private Item(int size) { this.size = size; }
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Base value = new Item();
        Class<?> type = value.getClass();
        System.out.println("type: " + type.getName());
        System.out.println("fields: " + Arrays.stream(type.getDeclaredFields())
                .map(Field::getName).sorted().toList());
        System.out.println("constructors: " + type.getDeclaredConstructors().length);
        var constructor = type.getDeclaredConstructor(int.class);
        System.out.println("int constructor is private: " + Modifier.isPrivate(constructor.getModifiers()));
        System.out.println("annotation present: " + type.isAnnotationPresent(Audited.class));
        System.out.println("annotation declared: " + (type.getDeclaredAnnotation(Audited.class) != null));
    }
}

Result

type: Main$Item
fields: [label, size]
constructors: 2
int constructor is private: true
annotation present: true
annotation declared: false

The variable is declared as `Base`, but the object is an `Item`. The sorted field list includes private `size` but not inherited `inheritedId`. The program finds the private `int` constructor without invoking it. `Audited` comes from `Base`; it is not directly declared on `Item`.

Related lessons

  • Java · Lesson 59 · Advanced · Version: 2

Sources