tags:

views:

563

answers:

9

Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.

Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:

  1. Given a config file with lines like
    x = "Hello World!"
    y = 5.0
    dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)

  2. When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.

  3. When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
    !some_command arg1 arg2
    into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.

  4. When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.

So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.

+1  A: 

There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.

If I think a bit longer I can probably come up with more examples.

Mendelt
+1  A: 

Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.

Command line parsing. Building up a config object based on the command line parameters that are passed in.

When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).

Aaron Maenpaa
+1  A: 

I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.

(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)

sectrean
+1  A: 

Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).

jodonnell
+1  A: 

I've used reflection to get current method information for exceptions, logging, etc.

            string src = MethodInfo.GetCurrentMethod().ToString();
            string msg = "Big Mistake";
            Exception newEx = new Exception(msg, ex);
            newEx.Source = src;

instead of

            string src = "MyMethod";
            string msg = "Big MistakeA";
            Exception newEx = new Exception(msg, ex);
            newEx.Source = src;

It's just easier for copy/paste inheritance and code generation.

jrcs3
What exactly would be "copy/paste inheritance"? And don't you have a stack trace in your exception anyway?
Groo
In the case where I used this, the exception was eventually logged to a text file and the stack trace wasn't logged.
jrcs3
+1  A: 

I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.

drewh
+7  A: 

I can list following usage for reflection:

  • Late binding
  • Security (introspect code for security reasons)
  • Code analysis
  • Dynamic typing (duck typing is not possible without reflection)
  • Metaprogramming

Some real-world usages of reflection from my personal experience:

  • Developed plugin system based on reflection
  • Used aspect-oriented programming model
  • Performed static code analysis
  • Used various Dependency Injection frameworks
  • ...

Reflection is good thing :)

aku
+1  A: 

I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.

As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data. If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...

Argelbargel
+1  A: 

I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.

There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.

If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.

You could even implement your own imperfect reflection that way.

For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.

davenpcj