''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): * '''Performance''' : Reflection is slower than direct invocation. * '''Maintainability''' * Hard to determine who has call dependencies on an object. * Misspelled method/class names as strings that are converted to object/method references are hard to test for. * ''Any'' object is subject to being controlled by any other (no contract required). * Source can be hard to read and trace. * '''Error Discovery and Handling''' : The compiler won't catch reference problems, they must be properly handled during runtime. * Realizing that Java is '''not'' Smalltalk and will never be... * Very difficult to refactor a code based on reflection. -- 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]