Java Reflection API

Ashutosh Kumar Singh
3 min readApr 7, 2024

--

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:

  1. We can create our own annotation processor using Reflection.
  2. It is used in testing and debugging.
  3. 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 that Class 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

  1. 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.

  1. 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:

  1. It comes with performance overhead, it makes program slow.
  2. 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! 😊

--

--

Ashutosh Kumar Singh
Ashutosh Kumar Singh

Written by Ashutosh Kumar Singh

0 Followers

Full Stack Developer

No responses yet