What is Reflection API in Java?

The Reflection API in Java allows a program to inspect and manipulate classes, methods, constructors, fields, and objects at runtime, even if their details are not known during compilation.

In simple terms, reflection lets Java analyze and modify its own structure while the program is running.





🔹 Why Reflection API is Used

  • To get class information dynamically

  • Access private fields and methods

  • Create objects at runtime

  • Invoke methods dynamically

  • Used heavily in frameworks like Spring and Hibernate


🔹 Important Classes in Reflection Package

Reflection API is available in:

java.lang.reflect

Common classes:

  • Class

  • Method

  • Field

  • Constructor


🔹 Example of Reflection

class Student {
    private String name = "Rahul";

    public void display() {
        System.out.println("Hello Student");
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("Student");

        Object obj = cls.getDeclaredConstructor().newInstance();

        java.lang.reflect.Method method =
                cls.getMethod("display");

        method.invoke(obj);
    }
}

Here, the method is called dynamically at runtime using reflection.


🔹 Advantages

  • Dynamic class loading

  • Useful for frameworks and tools

  • Reduces tight coupling

  • Enables runtime inspection


🔹 Disadvantages

  • Slower performance

  • Breaks encapsulation

  • Security risks if misused

  • Harder to maintain code


✅ Promotional Content

To understand advanced Java topics like Reflection API, JVM internals, Spring framework concepts, and real-time development practices, join the Top Java Real Time Projects Online Training in Ameerpet.

Comments

Popular posts from this blog

Spring Boot Microservices Development

Recursion & Dynamic Programming