Problems With Reflection


As you've seen, you can do some very cool things using reflection. Reflection is almost essential for some applications. JUnit currently depends heavily upon reflection. Many other Java technologies require the use of reflection, including EJBs and JavaBeans. Reflection can allow you to accomplish tasks that would otherwise be virtually impossible to do in Java. However, you should approach the use of reflection with caution.

First, code using reflection can be hard to decipher and debug. Modern IDEs, such as Eclipse, go a long way toward helping you easily navigate a system. Eclipse, for example, allows you to find all references to a class or a method. It cannot, however, as effectively find code that uses reflection to create the class or method call you are interested in. Reflection introduces a hole in your code's traceability!

Code that uses reflection executes considerably slower than equivalent code that does not use it. When you introduce reflection code that will be used frequently or on a large scale, profile it to ensure that it executes in a timely fashion.

Finally, when you use reflection, you code can exhibit defects that you might have otherwise caught at compile time. You must ensure that you code defensively, for example by dealing with the ClassNotFoundException that could be thrown by Class.forName.

Don't use reflection for the sake of using reflection.


This is Jeff's Rule of Statics (from Lesson 4) applied to reflection.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net