Applications for reflection

I recently spoke with a C ++ colleague and complained that there is no way to take a string with the name of a class field and extract a field with that name; in other words, he lacks reflection. He looked at me puzzled and asked when someone would need to do this.

On top of my head, I didn’t have a good answer for him, except "hey, I need to do this right now." So I sat down and came up with a list of some of the things that I actually did with reflection in different languages. Unfortunately, most of my examples are taken from my Python web programming, and I was hoping people would have more examples here. Here is the list I came up with:

  • Given a config file with lines, for example, x = "Hello World!"
    y = 5,0 - dynamically set the fields of some config object to equal values ​​in this file. (This was what I would like to do in C ++, but really could not do it.)

  • When sorting a list of objects, sort by an arbitrary attribute, given the attribute name from the configuration file or web request.

  • When writing software that uses a network protocol, reflection allows you to invoke methods based on the string values ​​of that protocol. For example, I wrote an IRC bot that will broadcast !some_command arg1 arg2
    into the actions.some_command(arg1, arg2) method call actions.some_command(arg1, arg2) and print any function returned back to the IRC channel.

  • When using the Python __getattr__ function (like my method_missing method in Ruby / Smalltalk), I worked with a class with a lot of statistics, like late_total. For each statistic, I would like to add _percent to get this statistic as a percentage of the total amount that I was calculating (e.g. stats.late_total_percent). Reflection made this very easy.

So can anyone here give examples from their own programming experience when thinking was helpful? The next time my interlocutor asks me why I “would like to do something like this,” I would like to be more prepared.

+18
reflection
Sep 08 '08 at 13:46
source share
9 answers

I can indicate the following use for reflection:

  • Late binding
  • Security (trouble code)
  • Code analysis
  • Dynamic typing (duck printing is not possible without reflection)
  • Metaprogramming

Some real reflection actions from my personal experience:

  • Developed reflection based plugin system
  • The aspect-oriented programming model used
  • Static code analysis performed
  • Different injection systems used for dependencies
  • ...

Reflection is good :)

+14
Sep 08 '08 at 14:08
source share

I 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

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

It is easier to copy and paste inheritance and code generation.

+4
Sep 08 '08 at 14:01
source share

Now I am in a situation where I have an XML stream entering the wire and I need to create an instance of the Entity object that will be populated from the elements in the stream. It is easier to use reflection to figure out which Entity object can process which XML element than to write a giant conditional nightmare operator. There is clearly a relationship between the XML schema and the way I build and name my objects, but I control them, so this is not a big problem.

+3
Sep 08 '08 at 14:06
source share

There are many times when you want to dynamically create instances and work with objects where the type is unknown before execution. For example, with OR-mappers or in the plugin architecture. Variable structures use it if you want to write a journal library and dynamically want to examine the type and properties of exceptions.

If I think a little longer, I might come up with more examples.

+2
Sep 08 '08 at 13:52
source share

I believe that reflection is very useful if the input (for example, xml) has a complex structure that can easily be mapped to object instances or I need some kind of “connection” between the instances.

Since reflection in Java is pretty simple, I sometimes use it for simple data (key cards), where I have a small fixed set of keys. It’s easy for one of them to determine if the key is valid (if the class has setter setKey (String data)), on the other hand, I can change the type of input data (text) and hide the conversion (for example, a simple translation of int to getKey ()) Therefore, the rest of the application can rely on correctly entered data. If the type of a certain key-value pair changes for one object (for example, form int to float), I only need to change it in the data object and its users, but I do not need to keep in mind the parser too. This may not be a reasonable approach. if performance is a problem ...

+2
Sep 08 '08 at 14:46
source share

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

Parsing the command line. Creating a configuration object based on command line parameters that are passed.

It is useful to use reflection when writing unit tests, although I mainly used this to bypass access modifiers (Java).

+1
Sep 08 '08 at 13:52
source share

I used reflection in C # when in the structure or in a third-party library that I wanted to access, a built-in or private method was built in.

(Disclaimer: This is not necessarily the best practice, because private and internal methods can be changed in later versions, but it worked for what I needed.)

+1
Sep 08 '08 at 13:55
source share

Well, in statically typed languages, you want to use reflection anytime you need to do something "dynamic". It is useful for tooling purposes (scanning elements of an object). In Java, it is often used in JMX and dynamic proxies. And there are tons of one-time cases where this is really the only way to go (almost anytime you need to do something that the compiler won't let you do).

+1
Sep 08 '08 at 13:55
source share

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

There is, however, a way to do what you want (ed). Use a hash table. Save the fields with the field name.

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

You could even realize your own imperfect reflection in this way.

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

+1
Sep 21 '08 at 1:18
source share



All Articles