The Java Reflection API enables a program to inspect and interact with classes, methods, constructors, fields, and annotations at runtime without knowing their details during compilation. It provides dynamic behavior, making it possible to create objects, invoke methods, and access class metadata while the application is running.
Key Points: • Reflection allows runtime inspection of class structure, including methods, fields, constructors, and annotations. • It is widely used by frameworks such as Spring, Hibernate, JUnit, and dependency injection containers. • Reflection offers great flexibility but may impact performance and can bypass encapsulation, so it should be used carefully.
Example: When Spring creates and injects objects automatically based on annotations such as @Component or @Autowired, it uses Reflection to discover class information and invoke constructors or methods at runtime.
Code Example:
import java.lang.reflect.Method;
class Employee {
public void display() {
System.out.println(
"Employee Details");
}
}
public class Main {
public static void main(String[] args)
throws Exception {
Class<?> clazz =
Employee.class;
Object object =
clazz.getDeclaredConstructor()
.newInstance();
Method method =
clazz.getMethod("display");
method.invoke(object);
}
}Interview Tip: A concise interview answer is: The Reflection API allows Java applications to examine and manipulate classes, methods, fields, and constructors at runtime. It is commonly used by frameworks like Spring and Hibernate for dependency injection, object creation, annotation processing, and dynamic method invocation, but it should be used carefully due to performance and security considerations.