Reflection API in Java
🔹 What is Reflection API in Java?
Reflection API in Java allows a Java program to:
Inspect classes at runtime
Access methods, fields, and constructors dynamically
Invoke methods or modify fields without knowing them at compile time
In simple words:
Reflection allows Java code to examine and manipulate its own structure during runtime.
🔹 Why Does Reflection Exist in Java?
Java is heavily used for:
Enterprise applications
Frameworks
Configuration-driven systems
Frameworks like Spring, Hibernate, JUnit:
Do NOT know your classes at compile time
Need to load classes dynamically
Need to call methods based on configuration or annotations
Reflection exists to support frameworks and dynamic behavior in Java.
Without Reflection:
Dependency Injection would not work
Annotations would be useless
Plugin systems would be impossible
🔹 What Problem Does Reflection Solve?
Without Reflection (Normal Java):
Tight coupling
Class must exist at compile time
No flexibility
With Reflection:
Class name from configuration
Loose coupling
Dynamic behavior
This is the core problem Reflection solves.
🔹 When Do We Actually Need Reflection?
Reflection is used when:
Class name comes from a config file
Behavior is decided at runtime
Framework scans annotations
Tools inspect unknown classes
⚠️ Business logic rarely needs Reflection.
Frameworks need it heavily.
🔹 Reflection API Packages & Core Classes
Reflection API mainly lives in: [Link]
Important classes:
Class
Method
Field
Constructor
Everything starts with the Class object.
🔹 How to Get Class Object (Entry Level)
1. Using .class
2. Using getClass()
3. Using [Link]() (MOST IMPORTANT)
📌 Frameworks mostly use [Link]().
🔹 Creating Objects Using Reflection
Normal Way:
Reflection Way:
👉 Object created without new keyword
👉 Class name can come from configuration
🔹 Accessing and Invoking Methods Using Reflection
Here:
Method name is resolved at runtime
Compiler does not verify method existence
⚠️ Errors appear at runtime, not compile time.
🔹 Accessing Fields (Including Private Fields)
⚠️ This breaks encapsulation.
Reflection can:
Access private fields
Modify internal state
That’s why it is powerful but dangerous.
🔹 Reflection vs Compile-Time in Java (Key Concepts)
Aspect Normal Java (Compile-Time) Reflection
Type Safety Yes No
Performance Fast Slower
Error Detection Compile Time Runtime
Flexibility Low High
💡 Quick Insight
Normal Java → Safer, faster, preferred for business logic
Reflection → Powerful, flexible, mainly used in frameworks (Spring, Hibernate, JUnit)
👉 Reflection shifts errors from compile time to runtime.
🔹 Reflection and Type Safety (Often Missed)
Object obj = [Link]().newInstance();
Compiler does not know the actual type
Casting errors may occur at runtime
Frameworks handle this internally to keep your code clean.
🔹 Reflection at Configuration Level (VERY IMPORTANT)
Example: Config-Driven Object Creation
[Link]
[Link]=[Link]
👉 Class decided by configuration, not code.
This is the foundation of:
Dependency Injection
Plugin systems
Inversion of Control
🔹 Reflection + Annotations (Framework Backbone)
Framework workflow:
1. Scan classpath
2. Read annotations using Reflection
3. Create objects dynamically
4. Inject dependencies
👉 This is how Spring works internally.
🔹 Reflection and JVM Internals (Clear & Simple)
Reflection works with:
ClassLoader → loads class
Metaspace → stores class metadata
Flow:
1. ClassLoader loads class
2. Metadata stored in Metaspace
3. Reflection reads metadata
4. JVM invokes methods dynamically
Reflection does NOT store data
It only reads existing metadata
🔹 Reflection at JVM Configuration Level
Reflection itself has no direct JVM flag, but it impacts:
Class loading frequency
Metaspace usage
Startup time
Memory pressure
Relevant JVM config: -XX:MaxMetaspaceSize=256m
Why?
Heavy Reflection → many classes loaded
Proxies generated dynamically
Metaspace can overflow
🔹 Reflection and Dynamic Proxies (Advanced but Essential)
Reflection enables dynamic proxies:
Used for:
Logging
Transactions
Security
AOP
Concept: [Link](...)
This is how:
Spring AOP
Method interception works
🔹 Reflection and MethodHandles (Advanced Insight)
Reflection is flexible but slower.
Java introduced MethodHandles:
Faster
JVM-friendly
Controlled dynamic invocation
Interview insight:
Reflection = flexibility
MethodHandles = performance + control
🔹 Reflection and Java Modules (Java 9+)
Java modules restrict Reflection to:
Protect encapsulation
Improve security
This explains:
Illegal reflective access warnings
Reflection failures in production
🔹 Performance Impact of Reflection
Reflection is slower because:
Resolved at runtime
JVM optimizations are limited
Best practices:
Avoid in loops
Cache reflected objects
Let frameworks handle it
🔹 When NOT to Use Reflection
If class is known at compile time
In performance-critical code
For simple design problems
Use Reflection only when necessary.
🔹 Complete End-to-End Example
✔ No direct class reference
✔ Fully runtime-driven execution
Final Summary :
Reflection API in Java enables runtime inspection and manipulation of classes, methods, and fields,
making frameworks flexible and configuration-driven, while requiring careful use due to performance
and security concerns.
🔥 Top 40 Frequently Asked Interview Questions & Answers
Q 1. What is Reflection API in Java?
Answer:
Reflection API allows a Java program to inspect classes, methods, fields, and constructors at runtime
and perform operations on them even if they are not known at compile time.
Q 2. Why does Java provide Reflection?
Answer:
Java provides Reflection to support frameworks and libraries that need to work with unknown classes
at runtime, such as Spring, Hibernate, and JUnit.
Q 3. Is Reflection used in normal business logic?
Answer:
No. Reflection is mainly used by frameworks. Using Reflection directly in business logic is discouraged
due to performance and maintenance issues.
Q 4. Which package contains Reflection API?
Answer:
The Reflection API is mainly present in the [Link] package.
Q 5. What is the Class object in Reflection?
Answer:
The Class object represents the runtime metadata of a class. It is the entry point for all reflection
operations.
Q 6. How can you get a Class object in Java?
Answer:
There are three ways:
1. [Link]
2. [Link]()
3. [Link]("fullyQualifiedName")
Q 7. Which way of getting Class object is mostly used by frameworks?
Answer:
[Link]() is mostly used by frameworks because the class name can be provided dynamically
through configuration.
Q 8. Can Reflection create objects without new keyword?
Answer:
Yes. Reflection can create objects using constructors obtained at runtime via
getDeclaredConstructor().newInstance().
Q 9. How do you invoke a method using Reflection?
Answer:
By obtaining a Method object using getDeclaredMethod() and invoking it using [Link](object).
Q 10. Can Reflection access private fields and methods?
Answer:
Yes. Reflection can access private members by calling setAccessible(true), but this breaks
encapsulation and should be used carefully.
Q 11. Does Reflection break encapsulation?
Answer:
Yes. Reflection can bypass access modifiers like private, which is why it is powerful but risky.
Q 12. What is the performance impact of Reflection?
Answer:
Reflection is slower than normal method calls because method resolution happens at runtime and
JVM optimizations are limited.
Q 13. Why is Reflection slower than normal method calls?
Answer:
Because Reflection involves runtime lookup, security checks, and dynamic dispatch, which adds
overhead.
Q 14. How do frameworks reduce Reflection performance cost?
Answer:
Frameworks cache reflected objects like Method, Field, and Constructor to avoid repeated lookup.
Q 15. What is setAccessible(true) used for?
Answer:
It disables Java language access checks, allowing access to private members.
Q 16. What are the security concerns of Reflection?
Answer:
Reflection can expose private data, modify internal state, and bypass security checks, which can lead
to vulnerabilities if misused.
Q 17. How does Reflection relate to Dependency Injection?
Answer:
DI frameworks use Reflection to create objects, inject dependencies, and wire components
dynamically based on configuration or annotations.
Q 18. How does Spring use Reflection?
Answer:
Spring uses Reflection to:
Scan classes
Read annotations
Create beans
Inject dependencies
Apply AOP proxies
Q 19. How does Reflection work with annotations?
Answer:
Reflection reads annotation metadata at runtime to determine behavior such as component scanning,
transaction management, and validation.
Q 20. Can Reflection be used to change method behavior?
Answer:
No. Reflection can invoke methods and access fields but cannot change method implementation.
Proxies are used for behavior interception.
Q 21. What are dynamic proxies in Java?
Answer:
Dynamic proxies allow runtime creation of proxy objects that intercept method calls, commonly used
in logging, security, and transactions.
Q 22. Can Reflection cause memory leaks?
Answer:
Yes. Improper class loading or proxy generation using Reflection can cause Metaspace memory leaks.
Q 23. What happens if Reflection fails at runtime?
Answer:
It throws runtime exceptions such as ClassNotFoundException, NoSuchMethodException, or
IllegalAccessException.
Q 24. Why are Reflection errors hard to debug?
Answer:
Because errors occur at runtime and are not caught during compilation.
Q 25. When should Reflection be avoided?
Answer:
Reflection should be avoided when:
Classes are known at compile time
Performance is critical
Simpler design is possible
Q 26. Can Reflection be used in multithreading?
Answer:
Yes, but reflection objects should be cached and thread safety must be ensured.
Q 27. Is Reflection thread-safe?
Answer:
Reflection API itself is thread-safe, but accessed objects must be handled carefully.
Q 28. What exceptions are commonly thrown by Reflection?
Answer:
ClassNotFoundException
NoSuchMethodException
IllegalAccessException
InvocationTargetException
Q 29. What is the biggest advantage of Reflection?
Answer:
Runtime flexibility and dynamic behavior.
Q 30. What is the biggest disadvantage of Reflection?
Answer:
Performance overhead, loss of type safety, and security risks.
Author:Krishna Makwana