Java Reflection No Panacea

This could be controversial. Please share your opinions!


Java Reflection is Not a Panacea

Problem: You have some classes with no common ancestry or interface (they have wildly diverging method signatures) and you need to invoke methods of an object (where the object type or method signatures are not known during compile time).

Potential Solution #1: You reach for the reflection API.

Potential Solution #2: You notice that this (anti)idiom is missing a context. You go back and figure out your context and ask yourself:

  1. Is there a language mechanism that will help me do this?
  2. Is performance important?
  3. Is there a finite enough set of classes/methods that it worth either coding up support code or squeezing out a common interface or ancestor?

Therefore: Consider all of your options and if there are no viable alternatives, use reflection.

When a Java developer finally understands the power of reflection, there can be a tendency to resort upon this dynamic facility at the drop of the hat.

The cost is (sometimes):

-- ToddCoram

The "therefore" line was originally "Consider all of your options and if there are no viable alternatives, FallBackOnReflection."

However, FallBackOnReflection is not a pattern that is used if one cannot "squeeze out a common interface". FallBackOnReflection is used to implement abstract interfaces for which many boilerplate implementations are required. The advantage is that you have a well-defined contract between implementers and callers of the interface and reflection can be replaced by a hand-coded implementation when performance is important. -- NatPryce


See also ReflectionVsCodeGenerationArticle.


[CategoryReflection]


EditText of this page (last edited March 8, 2003) or FindPage with title or text search