Java Code Geeks

Sunday, August 19, 2012

When to use java refection

Recently I faced with this question when to use java reflection? Many frameworks use it but we still keep saying do not use it in day to day work.  What's the real deal with it?
There are some real problems with using reflection,  java reflection is a hack from java compiler perspective. Reflection takes away all the compile time type checking of java and makes it more like a dynamic programming language. So compiler does not able to catch errors at the compile time but errors are thrown at the runtime. No IDE can refactor code written with reflection. If you refactor and change the signature of  the method, build will be fine but at runtime the code can fail because some code was using reflection to invoke the method with its old signature. These are some real reasons why we try to stay away from reflection. Above all of these there are performance issues also. Direct method call may be two to fifty times faster than the reflection counterpart, this is however very use case specific but in general, code with reflection runs slower on JVM.
But reflection is a powerful technique and it has a very clear use case. At the time of compilation if component A has no knowledge of component B but at the runtime, A wants to use classes of B, then A needs to use reflection. Example, Junit framework has no idea what test classes we are going to develop, so it needs to use reflection to understand the test class and methods. Hope this will clear the doubts in your mind as when to use reflection and not.

No comments: