I first came across reflection when I needed to develop a PHP framework for my former firm. I started by reading the fuel source code (fuel is a PHP framework) and came across the reflection patterns in the boot strap. I seem to have a lot of first times with PHP. Well I have come across it in Java too – the Android framework has some.
Reflection is the ability of a program to examine and modify the structure and behaviour of objects at runtime. Thus you can change values, metadata, functions and properties. Imagine resetting the value of a private variable in an object – well it is possible through reflection.
Imagine being able to inspect classes, fields, interfaces and methods at runtime without knowing their names or types; furthermore you can create new objects and call methods on them! Pretty cool huh? Through reflection, an executing program can do type introspection and manipulate internal properties. This feature is extremely powerful and does not exist in languages like C, Fortran or Pascal. Reflection allows you to get runtime access to a variety of class information.
Personally, I have not used reflection in development – I just haven’t had the reason to, maybe if I have to write a code analyzer though. Reflection can be used to clone objects; say you don’t know the details of a particular class and need to copy its properties; you can use reflection to copy all its contents. It is also awesome for plugin-type architectures; it comes when you need to load libraries blindly – maybe that’s why it is so popular with PHP frameworks. GUI applications and code inspection tools also use it to figure out what components are available to load or test at runtime. It can also eliminate the need to hardcode variables and write programs that ‘write’ programs to do what you want.
But isn’t it somewhat unnerving that reflection can be used to pry apart classes at runtime? Yah… there are some cons of reflection. Reflection code is much slower at accessing fields and methods and should not be used in performance-critical code. It also leads to obscure code – I learnt this the hard way reading the fuel source code – reflection code is typically more complex and verbose. It’s best to use it when it is really important and please remember to document it well.
Reflection is a cool concept and allows you to do wonderful stuff; but watch how you use it.