Java Reflection API
What is Reflection API?
Java’s Reflection API is unique feature that enable us to inspect and modify the information of class and its members at runtime.
Uses of Reflection
There are many ways we can use Reflection depending on our use-cases. Few of the use-cases are:
- We can create our own annotation processor using Reflection.
- It is used in testing and debugging.
- It is used in Spring extensively.
How to use Reflection?
- To use Reflection, we need to use classes available in
java.lang.reflect
package. - And, we need to get an object of
Class
class.Class
represent classes at runtime. - JVM creates a
Class
object for every class loaded at runtime, and thatClass
object contains meta-information. - Before getting started below is the Horse class we are going to reflect.
- Now the next question arises, “How to get object of associated
Class
class?”. There are 3 ways.
- Using Class object we can get many information.
<?>
is WildCard to represent modeled class.
Output:
Getting method details
- using getMethods():
2. using getDeclaredMethods():
3. Another ways are to target specific method.
How to invoke a method?
We can use invoke()
method, it takes instance of the Horse and method parameters if any.
Getting Field Details
Similar to Method we have Field class.
- getFields():
2. getDeclaredFields():
3. Another ways are to target specific field.
How to set field value?
We can use set()
method.
For private fields, above steps will throw exception. We need to use getDeclaredField()
and we need to make private field accessible and then we can set it.
Disadvantages of Reflection:
- It comes with performance overhead, it makes program slow.
- It breaks abstraction making private fields and methods accessible as well. It breaks singleton pattern by making private constructor accessible.
Conclusion
I hope you really enjoyed reading about Reflection. Remember, with power comes responsibility. If Reflection is giving you access then you should take responsibility of maintaining security of program. Happy Learning and Happy Coding! 😊