1.

What is the importance of reflection in Java?

Answer»
  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to SCAN the object and identify if it has any method called “fooBar()” and only then call the method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);methodOfFoo.invoke(fooObject, null);
  • Using reflection has its own cons:
    • Speed — Method INVOCATIONS due to reflection are about three TIMES slower than the direct method calls.
    • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
    • Traceability — Whenever a REFLECTIVE method fails, it is very difficult to find the root cause of this FAILURE due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.


Discussion

No Comment Found