<p>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.</p>

<p>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:</p>

<ol>
<li><p>Given a config file with lines like<br>
x = "Hello World!"<br>
y = 5.0<br>
dynamically set the fields of some <code>config</code> object equal to the values in that file.  (This was what I wished I could do in C++, but actually couldn't do.)</p></li>
<li><p>When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.</p></li>
<li><p>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<br>
<code>!some_command arg1 arg2</code><br>
into a method call <code>actions.some_command(arg1, arg2)</code> and print whatever that function returned back to the IRC channel.</p></li>
<li><p>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.</p></li>
</ol>

<p>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.</p>

[{'answer_id': 49748, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<p>If I think a bit longer I can probably come up with more examples.</p>\n"}, {'answer_id': 49749, 'author': 'Aaron Maenpaa', 'author_id': 2603, 'author_profile': 'https://Stackoverflow.com/users/2603', 'pm_score': 1, 'selected': False, 'text': "<p>Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.</p>\n\n<p>Command line parsing. Building up a config object based on the command line parameters that are passed in.</p>\n\n<p>When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).</p>\n"}, {'answer_id': 49751, 'author': 'John Rutherford', 'author_id': 3880, 'author_profile': 'https://Stackoverflow.com/users/3880', 'pm_score': 1, 'selected': False, 'text': "<p>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.</p>\n\n<p>(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.)</p>\n"}, {'answer_id': 49752, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 1, 'selected': False, 'text': '<p>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).</p>\n'}, {'answer_id': 49760, 'author': 'jrcs3', 'author_id': 3819, 'author_profile': 'https://Stackoverflow.com/users/3819', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve used reflection to get current method information for exceptions, logging, etc.</p>\n\n<pre><code>string src = MethodInfo.GetCurrentMethod().ToString();\nstring msg = "Big Mistake";\nException newEx = new Exception(msg, ex);\nnewEx.Source = src;\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>string src = "MyMethod";\nstring msg = "Big MistakeA";\nException newEx = new Exception(msg, ex);\nnewEx.Source = src;\n</code></pre>\n\n<p>It\'s just easier for copy/paste inheritance and code generation.</p>\n'}, {'answer_id': 49768, 'author': 'drewh', 'author_id': 1967, 'author_profile': 'https://Stackoverflow.com/users/1967', 'pm_score': 2, 'selected': False, 'text': "<p>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. </p>\n"}, {'answer_id': 49771, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 5, 'selected': True, 'text': '<p>I can list following usage for reflection:</p>\n\n<ul>\n<li>Late binding</li>\n<li>Security (introspect code for security reasons)</li>\n<li>Code analysis</li>\n<li>Dynamic typing (duck typing is not possible without reflection)</li>\n<li>Metaprogramming</li>\n</ul>\n\n<p>Some real-world usages of reflection from my personal experience:</p>\n\n<ul>\n<li>Developed plugin system based on reflection</li>\n<li>Used aspect-oriented programming model</li>\n<li>Performed static code analysis</li>\n<li>Used various Dependency Injection frameworks</li>\n<li>...</li>\n</ul>\n\n<p>Reflection is good thing :)</p>\n'}, {'answer_id': 49850, 'author': 'Argelbargel', 'author_id': 2992, 'author_profile': 'https://Stackoverflow.com/users/2992', 'pm_score': 2, 'selected': False, 'text': '<p>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. </p>\n\n<p>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.\nIf 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...</p>\n'}, {'answer_id': 109923, 'author': 'davenpcj', 'author_id': 4777, 'author_profile': 'https://Stackoverflow.com/users/4777', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n\n<p>There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.</p>\n\n<p>If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. <code>#define GetX() Get("X")</code> sort of thing.</p>\n\n<p>You could even implement your own imperfect reflection that way.</p>\n\n<p>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.</p>\n'}]
['https://Stackoverflow.com/questions/49737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1694/']