🔍 What is Reflection in Java?
Reflection is the ability of a Java program to inspect, analyze, and even modify itself at runtime — meaning you can inspect classes, methods, fields, and constructors even if you don’t know them at compile time.
🧰 What can you do with Reflection?
With reflection, you can: ✅ Discover class name at runtime.
✅ Discover methods, fields, and constructors.
✅ Call methods, even private ones.
✅ Change field values, even private ones.
✅ Create objects dynamically.
📦 Where does it live?
Reflection lives in the java.lang.reflect
package and the java.lang.Class
class.
🔥 Example Use Case
Let’s say you have a class:
public class Person {
private String name;
private int age;
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
Using Reflection
You can access this class even if you only have its name as a string:
Class<?> clazz = Class.forName("Person");
Object person = clazz.getDeclaredConstructor().newInstance();
// Set private field "name"
Field nameField = clazz.getDeclaredField("name");
nameField.setAccessible(true); // allows access to private field
nameField.set(person, "John");
// Call method "sayHello"
Method method = clazz.getMethod("sayHello");
method.invoke(person);
Output:
Hello, my name is John
🚀 Common Reflection Classes
Class | Purpose |
---|---|
Class | Represents a class (metadata) |
Field | Represents a field (variable) |
Method | Represents a method |
Constructor | Represents a constructor |
Modifier | Checks modifiers (public, private, static, etc.) |
📚 Typical Uses of Reflection
✅ Frameworks (like Spring, Hibernate — they scan and inject dependencies).
✅ Serialization (Java’s default serialization uses reflection).
✅ Unit testing (some testing frameworks use reflection to find and run test methods).
✅ Dependency Injection (Spring finds beans and injects them via reflection).
✅ Debugging tools and profilers.
✅ Plugin systems where you load unknown classes at runtime.
⚠️ Downsides of Reflection
❌ Performance – Slower than direct calls (reflection bypasses normal optimizations like inlining).
❌ Breaks Encapsulation – Can access private fields/methods.
❌ Complexity – Makes code harder to understand and maintain.
❌ Security – Can be dangerous if used carelessly.
💡 Summary
Aspect | Reflection |
---|---|
Power | Very powerful (can inspect and modify anything) |
Performance | Slower than normal code |
Safety | Can break encapsulation & type safety |
Use cases | Frameworks, tools, dependency injection |
Example library using reflection | Spring, Hibernate, JUnit |
🛠️ Quick analogy
Reflection is like a master key to your Java program — you can open any door, even ones marked private. Great power, but dangerous if misused.