Category: java
Java Reflection
Published on 23 Oct 2026
Explanation
Java Reflection is a feature that
allows a Java program to inspect
and interact with classes, methods, fields,
and constructors at runtime. It can
be used to discover class information
dynamically without knowing all the details
at compile time.
Code:
Class<?> clazz = String.class; System.out.println(clazz.getName()); System.out.println(clazz.getSimpleName()); System.out.println(clazz.getDeclaredMethods().length);
Explanation
Java Reflection provides the Class object,
which represents a class at runtime.
You can obtain it using ClassName.class,
object.getClass(), or Class.forName().
This information helps
developers inspect classes dynamically.
Code:
class Student {
private String name;
}
public class Main {
public static void main(String[] args)
throws ClassNotFoundException {
Class<?> clazz = Class.forName("java.lang.String");
System.out.println(clazz.getName());
System.out.println(clazz.getSimpleName());
}
}
Explanation
Reflection allows a program to inspect
private fields. With appropriate access permissions,
setAccessible(true) can enable access to a
private field. Modern Java module boundaries
may restrict this operation. Use reflection
carefully because it can bypass normal
encapsulation.
Code:
import java.lang.reflect.Field;
class Student {
private String name = "Arun";
}
public class Main {
public static void main(String[] args)
throws Exception {
Student student = new Student();
Field field = Student.class.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.get(student));
}
}
Explanation
Java Reflection can locate and invoke
a method at runtime using its
name and parameter types. This is
useful in frameworks, plugin systems, and
dynamic execution scenarios where the method
to call is determined at runtime.
Code:
import java.lang.reflect.Method;
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args)
throws Exception {
Calculator calculator = new Calculator();
Method method = Calculator.class.getMethod(
"add", int.class, int.class);
Object result = method.invoke(calculator, 10, 20);
System.out.println(result); // 30
}
}
Explanation
Reflection is widely used by Java
frameworks to discover annotations, create objects,
inject dependencies, map database records, and
execute test methods. For example, Spring
can inspect annotations such as @Component
and @Autowired to help configure application
objects
Code:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyComponent {}
@MyComponent
class StudentService {}
public class Main {
public static void main(String[] args) {
boolean present = StudentService.class
.isAnnotationPresent(MyComponent.class);
System.out.println(present); // true
}
}