What exactly is Reflection?
I read the Wikipedia article on this subject and I understand that it is a kind of meta-programming, where the program can modify itself at run-time, but what does this mean?
In what kind of situations is this a good approach and when is it the best to use it?
What exactly is Reflection? I read the Wikipedia article on this subject and I
Share
Reflection is a facility where you can query an object about its attributes at runtime. For example, Python, Java and .Net have facilities where you can find the instance variables or methods of an object.
An example of an application for reflection is an O/R mapping layer. Some use reflection to construct an object by quering its properties at runtime and dynamically populating an instance. This allows you to do this programatically based on metadata from some sort of data dictionary without having to recompile the application.
To take a simple example, I’ll use Python because its reflection facilities are very simple to use and involve less boilerplate than those of java or .Net.
Now, we’ve used basic reflection to examine the instance variables of an arbitrary object. The special variable
__dict__on Python is a system property of an object that has a hash table of its members keyed by the variable (or method) name. We have reflectively examined the object and used the reflection facilities to artificially poke a second instance variable into it, which we can then display by invoking it as an instance variable.Note that this particular trick doesn’t work on Java or .Net, as the instance variables are fixed. The type system of these languages doesn’t allow new instance variables to be added at runtime in the way that python’s ‘duck’ typing system does. However, you could have reflectively updated the value of an instance variable that was declared in the type definition.
You can also use reflection to dynamically construct method invocations and perform various other neat tricks such as instantiating an object based on a parameter. For example, if you had some sort of plugin based system where certain capabilities were optional, you could use reflection to query the plugin about what services it offered (perhaps by querying whether certain interfaces were implemented) without requiring explicit metadata.
Many dynamic language interfaces such as OLE automation use reflection as an integral part of the interface.