In this blog, we will cover the following points
- What is Reflection API?
- Using private methods
- Using private fields
- Sample Code
- Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.
- Take for example your typical web.xml file.
- This will contain a list of servlet elements, which contain nested servlet-class elements.
- The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.
- Another example would be the Java API for XML Parsing (JAXP).
- Where an XML parser provider is ‘plugged-in’ via well-known system properties, which are used to construct new instances through reflection.
- The most comprehensive example is Spring which uses reflection to create its beans, and for its heavy use of proxies
- When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument com.example.Foo to instantiate that class.
- It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.
- JUnit uses Reflection especially for testing Private/Protected methods.
Reflection for private methods
Reflection for private fields
- Reflection is also more powerful, you can retrieve the definition of a protected or final member, remove the protection and manipulate it as if it had been declared mutable!
- Reflection is much slower than just calling methods by their name because it has to inspect the metadata in the bytecode instead of just using precompiled addresses and constants.
- In the following example, we will see how we can use Reflection to get class info like constructor, methods. fields etc.