Java

Reflection API

Inspect and manipulate classes, methods, and fields at runtime using Java Reflection.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Inspect and manipulate classes, methods, and fields at runtime using Java Reflection. This hands-on tutorial focuses on practical implementation of reflection api concepts.

Reflection API

Reflection allows you to inspect and manipulate classes at runtime.

Getting Class Object

// Three ways
Class<?> cls1 = String.class;
Class<?> cls2 = "Hello".getClass();
Class<?> cls3 = Class.forName("java.lang.String");

Inspecting Class Members

Fields

Class<?> cls = MyClass.class;
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
    System.out.println(field.getName());
}

Methods

Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
    System.out.println(method.getName());
}

Constructors

Constructor<?>[] constructors = cls.getDeclaredConstructors();

Accessing Private Members

class Person {
    private String name = "Secret";
}

// Access private field
Field field = Person.class.getDeclaredField("name");
field.setAccessible(true); // Bypass private access
Person person = new Person();
String value = (String) field.get(person);
System.out.println(value); // "Secret"

Invoking Methods Dynamically

Method method = MyClass.class.getMethod("myMethod", String.class);
Object result = method.invoke(objectInstance, "parameter");

Use Cases

Use CaseExample
FrameworksSpring, Hibernate use reflection for DI
TestingJUnit uses reflection to find @Test methods
SerializationJackson, Gson use reflection for JSON
DebuggingInspecting objects at runtime

[!WARNING] Reflection is powerful but slow and can break encapsulation. Use sparingly!

JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Java Reflection API for runtime class inspection"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

What does reflection allow you to do?

Inspect classes at runtime
Compile code faster
Delete classes