Understanding and Using Reflection
Reflection is a powerful language feature. Java supports ‘structural-reflection’, which is safe to use. With reflection, it is possible to do two basic types of operations on code: inspection and manipulation. Reflection enables using ‘signature based polymorphism’ as an alternative to ‘interface based polymorphism’ in Java.Reflection also facilitates creation of flexible and adaptable frameworks and patterns, which is not usually possible with direct code. Though there are many clear advantages in using reflection,like any other language feature, reflection can be misused. This article covers a few specific problems and solutions to illustrate uses and misuses of reflection.
In programming, reflection is the ability to dynamically create, use or manipulateclasses and objects at runtime. For example, you can create an instance of a class,examine the class to find a specific method from that class and execute thatmethod with the arguments you specify, all this dynamically at runtime usingreflection.Reflection is not a new concept. Smalltalk – one of the early and important OOprogramming language – supported reflection in 1970s itself. Reflection is possibleonly when sophisticated runtime support is available in the languageimplementations. C++ follows static compilation model where the code is compiled tonative code and executed; the runtime support is limited. So reflection is notpossible in C++. However, Java and C# have sophisticated runtime mechanisms (JVMfor Java and CLR for .NET), so reflection can be supported in these languages.One of the misconceptions about reflection is that it is difficult to learn or use. Bylearning a few APIs and basic concepts, even beginners can write simple code usingreflection. However, like any other language feature, effective use of reflectiontakes effort and considerable experience.The reflection feature supported by languages like Java and C# is known as‘structural reflection’ where only inspection and execution of the code is allowed.There is another form of reflection more sophisticated than ‘structural reflection’,known as ‘behavioral reflection’, which allows us to modify or manipulate the code atruntime . For strongly-typed, commercially widely used languages like Java,‘structural reflection’ suffices.Reflection is a powerful feature and it is very useful for creating dynamic oradaptable design and for writing development tools. Reflection is also often misusedby the programmers. In this article, after a short example for showing a how wewrite reflection code in Java, we’ll see the advantages, disadvantages, uses andmisuses of reflection with focus on disadvantages and misuses of reflection.
Reflection Example: Class Dissection