Reflection in Java (original) (raw)

Last Updated : 14 Mar, 2026

Reflection in Java allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even when their details are unknown at compile time. It is provided through the java.lang.reflect package and is widely used in frameworks and libraries.

reflection_in_java

Overview of Java Reflection – class structure, workflow, and access control

Java Reflection API

Java provides reflection through the following key classes:

These classes are located in the java.lang and java.lang.reflect packages.

1. Getting Class Object in Java

Before performing any reflection operation, a Class object must be obtained. The Class object represents the runtime metadata of a class, such as its methods, fields, and constructors.

**Ways to Get Class Object

Java `

Class<?> c1 = Test.class;

Class<?> c2 = Class.forName("Test");

Test obj = new Test(); Class<?> c3 = obj.getClass();

`

2. Creating Objects Using Reflection

Reflection allows objects to be created dynamically at runtime without using the new keyword. This is done by retrieving a Constructor object and invoking it programmatically.

Java `

import java.lang.reflect.Constructor;

class Test { public Test() { System.out.println("Object Created"); } }

public class GFG { public static void main(String[] args) throws Exception { Constructor constructor = Test.class.getConstructor(); constructor.newInstance(); } }

`

**Explanation:

3. Accessing Methods Using Reflection

Using reflection, methods of a class can be discovered and invoked at runtime by their names. This is useful when method details are not known at compile time.

Java `

import java.lang.reflect.Method;

class Test { public void show() { System.out.println("Method Invoked"); } }

public class GFG { public static void main(String[] args) throws Exception { Test obj = new Test(); Method m = Test.class.getMethod("show"); m.invoke(obj); } }

`

**Explanation:

4. Accessing Fields Using Reflection

Reflection provides the ability to access and modify class fields dynamically, including private fields. This is achieved using the Field class and can bypass access restrictions if required.

Java `

import java.lang.reflect.Field;

class Test { private String msg = "Hello"; }

public class GFG { public static void main(String[] args) throws Exception { Test obj = new Test(); Field f = Test.class.getDeclaredField("msg"); f.setAccessible(true); System.out.println(f.get(obj)); } }

`

**Explanation:

Reflection vs Normal Code

Feature Reflection Normal Code
Compile-time Safety No Yes
Performance Slower Faster
Performance High Low
Security Lower Higher

**Note: