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