Java.Core.What is reflection in Java, and how is it used?

🔍 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

ClassPurpose
ClassRepresents a class (metadata)
FieldRepresents a field (variable)
MethodRepresents a method
ConstructorRepresents a constructor
ModifierChecks 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

AspectReflection
PowerVery powerful (can inspect and modify anything)
PerformanceSlower than normal code
SafetyCan break encapsulation & type safety
Use casesFrameworks, tools, dependency injection
Example library using reflectionSpring, 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.

This entry was posted in Без рубрики. Bookmark the permalink.