Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Reflection in Java

Reflection in Java: Reflection exposes runtime metadata and dynamic construction, field access, and method invocation through Class, Method, Field, and Constructor.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

reflection

Reflection exposes runtime metadata and dynamic construction, field access, and method invocation through Class, Method, Field, and Constructor.

Use it in plugin, serialization, or DI infrastructure, keep its scope narrow, and cache metadata that has already been validated.

Access checks and JPMS still apply; trySetAccessible can return false and forced access can cause InaccessibleObjectException.

A missing method throws NoSuchMethodException, while Method.invoke wraps the target exception in InvocationTargetException; erasure can also produce bridge methods.

getDeclaredMethod finds private greet(String), so stdout begins greet String; trySetAccessible yields true and invoke prints Hello, Ada.

Examples

import java.lang.reflect.Method;

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

    public static void main(String[] args) throws Exception {
        Method method = Greeter.class.getDeclaredMethod("greet", String.class);
        System.out.println(method.getName() + " " + method.getParameterTypes()[0].getSimpleName());
        System.out.println(method.trySetAccessible());
        System.out.println(method.invoke(new Greeter(), "Ada"));
    }
}

Result

greet String
true
Hello, Ada

getDeclaredMethod finds private greet(String), so stdout begins greet String; trySetAccessible yields true and invoke prints Hello, Ada.

Sources