Thursday, August 15, 2013

Why should I use reflection?

  • 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.
  • 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! Obviously this subverts many of the guarantees the language normally makes for your programs and can be very, very dangerous.
  • And this pretty much explains when you would use it. Ordinarily, don't. If you want to call a method, just call it. If you want to mutate a member, just declare it mutable instead of going behind the compile's back.
One useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where th framework author doesn't know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. For instance, I don't think it would be possible to write a complex aspect-oriented librory without reflection.
As another example, JUnit used to use a trivial bit of reflection: it enumerates all methods in your class, assumes that all those called testXXX are test methods, and executes only those. But this can now be done better with annotations instead, and in fact JUnit 4 has largely moved to annotations instead.

No comments:

Post a Comment