views:

468

answers:

11

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?

+11  A: 

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.

ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo:
...     def __init__(self):
...             self.x = 1
...
>>> xx = foo()      # Creates an object and runs the constructor
>>> xx.__dict__     # System metadata about the object
{'x': 1}
>>> a = xx.__dict__ # Now we manipulate the object through 
>>> a['y'] = 2      # its metadata ...
>>> print xx.y      # ... and suddenly it has a new instance
2                   # variable.
>>>

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.

ConcernedOfTunbridgeWells
Thanks, that really made it much more clear to me!
JPCosta
So this is how "scaffolding" works?
johnny
A: 

In Java it is basically a way to instantiate a class without knowing about it before hand. Say you want the user to be able to change a configuration file by adding the class they want your program to use (say you have numerous implementations of some interface). With reflection you can create an object based on just it's name, method signature, etc. . . and then cast it to your interface.

Gandalf
A: 

Reflection is useful for runtime configuration, allowing parts of a system to be driven through external configuration.

For example, a class factory could construct different concrete types based on an input file, where the concrete types require different configuration information to call a concrete constructor rather than using a builder interface. (The constructor method of the object being located using reflection).

Tetsujin no Oni
OK, how does a concrete example, with exactly the same use case as one of the later answers with upvotes, get downvotes?
Tetsujin no Oni
+1  A: 

The first good example I can think of off the top of my head is for when you need to execute a set of methods on a given object without knowing at compile-time what methods will exist in it.

Take unit testing frameworks for example. The test runner class that is responsible for running all your unit tests doesn't know ahead of time what you are going to name your methods. All it knows is that they will be prefixed with "test" (or in Java 5's case, annotated with @Test). So when given a test class, it reflects on that class in order to get a list of all the methods in it. Then, it iterates through those method names as strings and calls those methods on the object if they start with "test". That wouldn't be possible without reflection. And that's just one example.

Marc W
+7  A: 

It's not so much modifying code at execution time, but examining objects and asking them to execute code without knowing their type statically.

One simple way of describing it would be "a somewhat painful way of making a statically typed language behave dynamically."

EDIT: Uses:

  • Configuration (e.g. take an XML file which specifies types and properties, then construct appropriate objects)
  • Testing (unit tests which are identified by name or attributes)
  • Web services (in .NET at least, a lot of reflection is used in the core web service engine)
  • Automatic event wiring - provide a method with an appropriate name, e.g. SubmitButton_Click and ASP.NET will attach that method as a handler for the SubmitButton's Click event (if you have autowiring turned on)

Is it a good idea? Well, only when the alternatives are painful. I prefer static typing when it doesn't get in the way - then you get lots of compile-time goodness, and it's faster too. But when you do need it, reflection lets you do various things which otherwise just wouldn't be possible.

Jon Skeet
Jon give us some examples of when do you use it
Nuno Furtado
haha I like that description. +1
Spencer Ruport
Thanks for your answer!
JPCosta
+1  A: 

I'll give you an example.

As a programming exercise I wrote an mp3 file checker. It scans my music library and displays the id1/id2 tags I'm interested in in a DataGridView. I use reflection to get the properties from the mp3 info class without the UI code having to know anything about that class. If I want to change what information gets displayed I can either edit the mp3 info class or change its configuration (depending on how I wrote the class) and don't have to update the UI.

It's also meant that I've been able to use Dependency Injection to use the same from end to display information about digital photographs just by swapping the data library class.

ChrisF
A: 

Reflection has been useful to me in at least 1 project I can think of. We wrote an internal "Process Manager" program that performs a lot of key business processes at certain intervals. The project is set up so that the core is really just a windows service with timer objects that fire off every 30 seconds or so and check for work to do.

The actual work is being done in a class library (appropriately called "WorkerLib"). We define classes with public methods that perform certain tasks (moving files around, uploading data to remote sites, etc.) The idea is that the core service can call methods from the worker library without knowing anything about the methods it's calling. This allows us to create a schedule in the database for jobs, and even add new methods into the class library without ever having to alter the core system.

The basic idea is that we can use reflection in the core service to execute methods whose names we have stored in the database defining the schedules. It's pretty neat in practice. Our core service is solid and handles executing the jobs as needed, while the actual worker library can be expanded and changed as necessary without the core even caring.

If you need further explanation, please feel free to ask. This was simply the best way I could think of to explain a real-world scenario where reflection really makes things easier for us.

Scott Anderson
+1  A: 

Another example: I have code that I use that takes the output of a database - which is a set of rows with named columns - and feeds it into an array of objects. I iterate through the rows, and if the target object has a property with the same name and type, I set it. This makes for my data-getting code just looking something like this:

SqlDataReader sdr = Helper.GetReader("GetClientByID", ClientID);
Client c = new Client();
FillObject(sdr, c);
return c;
Aric TenEyck
A: 

Reflection is (basically) the ability of a program to query for type information that was available to the compiler. So, for example, given the name of a type you can query for the methods it contains. Then for each method you can query for the types of the parameters they take etc etc etc.

It's useful for runtime configuration where you've got a config file that specifies the behavior of your application. The config may contain the names of concrete types that you should use (as is often the case with IOC containers). Using reflection you can create an instance of this concrete type (via a reflection API) and use it.

Sean
A: 

Really, reflection should be thought of as sort of an amplifier for code. It can make good code better and cleaner, and bad code worse. What does it do? It really allows you to write code, that your not totally certain what it's going to do at the time you write it. You have a general idea, but it allows you to not code what objects, methods, and properties are going execute when the program is compiled.

Other posts are correct when they say it allows the program to execute code based on configuration values, but it's real power is that it allows you to severely bend the rules of object oriented programming. That's really what it does. It's kind of like turning the safety measures off. Private methods and properties can be accessed through reflection along with just about anything else.

An excellent example of when MS uses reflection is with data binding on data object. You specify the name of the text field and data field for an object to bind to a drop down list etc., and the code reflects the object and pulls out the appropriate information. The data binding object does the same process over and over again, but it doesn't know what type of object it has to bind with. Reflection is a convenient way of writing a little bit of code to handle all the possible cases.

Kevin