Hackforge Academy

Category: java

Reflection in Java

Published on 04 May 2026

Explanation

Reflection in Java is a feature that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even if their names are not known at compile time. It is part of the java.lang.reflect package.

Code:

Class<?> obj = Class.forName("
java.lang.String");
System.out.println(obj.getName());

Explanation

Using reflection, you can get information about a class such as its methods, fields, constructors, and annotations dynamically during runtime.

Code:

Class<?> cls = Class.forName("
java.lang.String");
Method[] methods = cls.getMethods();
for(Method m : methods) {
    System.out.println(m.getName());
}

Explanation

Reflection also allows you to create objects dynamically without using the 'new' keyword.

Code:

Class<?> cls = Class.forName(
"java.lang.String");
Object obj = cls.getDeclaredConstructor().
newInstance();
System.out.println(obj.toString());

Explanation

Real-time usage: Reflection is widely used in frameworks like Spring, Hibernate, and JUnit for dependency injection, ORM mapping, and testing.

Code:

// Example: Access private field 
//using reflection
class Test {
    private String name = "Java";
}

Class<?> cls = Test.class;
Field field = cls.getDeclaredField("name");
field.setAccessible(true);
Test t = new Test();
System.out.println(field.get(t));

Explanation

Advantages and Disadvantages: Reflection provides flexibility and dynamic behavior, but it can reduce performance and break encapsulation if not used carefully.

Code:

// Use reflection cautiously due 
to performance overhead

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community