Java Reflection
Tuesday, May 13th, 2008In a project I was confronted with a reason to use Java Reflection. What I found was a way to dynamically scale a class to find out its variables, methods, etc. During this process fortunately we changed gears and moved away from the design which was forcing this way of thinking. I have, ever since, been looking into it more and more and trying to discover why it isn’t more commonly used. Aside from the inherent complexity and detracting from readability I found a list of “draw backs” to using reflection which I will paste below:
http://java.sun.com/docs/books/tutorial/reflect/
Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
- Performance Overhead
- Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
- Security Restrictions
- Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
- Exposure of Internals
- Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing
privatefields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.