The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.


I've seen references made to reflection for a while now.  I did some looking around today and have a basic understanding of what it is now - at runtime, you can dynamically discover classes and use them, even if they were unknown at the time you wrote your code.

First, is that definition correct?

Next and more importantly, I have no clue when I would acutally want to do something using reflection?  I couldn't come up with anything that made sense so please, can someone enlighten me?

Andy Send private email
Thursday, June 09, 2005
Besides debugging, look at JUnit and similar QA tools. The framework looks for all methods in a class with the appropriate name and runs them.

Thursday, June 09, 2005
OK, a practical example. I reviewed some (Java) code a while ago that was a big else/else if block that branched based on the value of a string. The string essentially determined other methods that would be called, each having consistent method names that followed a convention and accepting the same arguments. It was a plug-in type thing.

The problem was that when you added a new "plug-in", not only did you have to add a new method to support it, but you had to add another "else if" to the branching code - horrible! I got the coder to replace the branching code with some code that used reflection to discover and invoke the appropriate method based upon the string value.
John Topley Send private email
Thursday, June 09, 2005
I think dynamic proxies are a good use of reflection in java

Generally relfection is useful for doing anything at the meta level, that is you write a program that writes the program to  do what you want. It's like taking database schema and then writing a program to take the schema to autogenerate all the stored procedures for accessing the tables. I think Model Driven Architecture stuff is in the right spirit these days.
son of parnas
Thursday, June 09, 2005
Here's an example of how Python's reflection can add intermediate steps in refactoring. Say I start out with two files, and
message_0 = 'hello'
message_1 = 'world'
message_2 = 'foo'
message_3 = 'bar'
import extra

print extra.message_0
print extra.message_1
print extra.message_2
print extra.message_3

It's pretty clear that this needs refactoring. It would be better like this:
messages = ['hello',
from extra import messages

for msg in messages:
    print msg

Without reflection, both files would need to be changed at the same time to complete the operation, so it's a one-step process. With reflection, I can change first:
import extra

for i in xrange(4):
    print getattr(extra, 'message_' + str(i))

That's compatible with the original version of I can change in a similar way:
messages = ['hello',

temp = {}
for i, msg in enumerate(messages):
    temp['message_'+str(i)] = msg


Conveniently, once I've made both of these changes, can be changed to our final version without change to After that's verified to work, we can just remove the excess code from to complete the refactoring.
Thursday, June 09, 2005
"I have no clue when I would acutally want to do something using reflection"

You may want to use reflection when you write a Java IDE.
A. Nonymous
Thursday, June 09, 2005
On my current project we just fixed a bunch of classes that (for various silly reasons) need to write their class names into a DB.  The class names were being set in a string, so when the package for the class changed, everything broke.

Using reflection to write the class name rather than a hard coded string tidies that up nicely.
Rodger Donaldson Send private email
Thursday, June 09, 2005
I've used to do all kinds of things. For example you can use to persist any class in and out of XML. If you decorate your properties and variables you can mark them as wanting to be persisted or not.
It is SLOW in .NET not so bad you'd hate to use it but if you want real speed you might want to use it to find out if a particular object supports an interface then cast the object to the interface and call it via the interface.
IIRC the Xml persistance classes in .NET actually write code that calls the class it's persisting at runtime then uses that to actually save the XML away, the time hit of compilation is less than the hit of using pure reflection.
(My guess would be for anything with more than 1000 elements)
Peter Ibbotson
Friday, June 10, 2005
I vaguely recall writing a method that did additional things if the class of the argument implemented certain interfaces.  In that case, I used reflection to get a list of the interfaces implemented.

I also wrote (for fun) a method that took field names as input and invoked their access methods -- kind of like JSPs do.  That left me with an unclean feeling, though.  :)

Another common use of reflection is in ClassLoaders and factory methods.  In general, I don't use it much, and like it that way.
Matt Brown Send private email
Friday, June 10, 2005
I occasionally use reflection in my Java programming, for two purposes.

1) Including a class name in a configuration file, and creating a member of that class

2) Allowing circular dependencies between compilation units. [That's a last resort when I can't find a clean way of eliminating the circular dependency.]

In the code base I've been writing for the last 4 years, reflection occurs a half-dozen times or so. Still, it's nice having the option available when necessary.
Saturday, June 11, 2005
The Python code is a contrived example if I ever saw one.

But I do love Python!
Ben Atkin Send private email
Sunday, June 12, 2005
"The Python code is a contrived example if I ever saw one."

It's loosely based on a real situation, so it's not quite as contrived as it seems. I admit it looks pretty stupid when simplified.
Sunday, June 12, 2005
I've used reflection to manage a couple of different situations.

In the first case, I was dealing with an external far file (this is Java) where I wasn't sure where the jar file would be or even if it would exist.  To make the code compile without the library present, I had to use reflection to access everything from the library.

In the second case, I was writing a routine that created function objects from strings.  I used reflection to decide whether the given function had been subclassed or not, and, if so, to call the factory method on it.  If it hadn't, I used a generic function object that just recorded the name and parameters.
Monday, June 13, 2005
As for Python and contrived examples: if you look at the wxWindows demo code in wxLayoutConstraints, there is a lot of code like

        lc = wxLayoutConstraints(), wxTop, 10)
        lc.right.SameAs(self, wxRight, 10)
        lc.bottom.PercentOf(self, wxBottom, 30)
        lc.left.RightOf(self.panelA, 10)

Initially I found wxLayoutConstraints very handy, but tedious to code. Then I noticed that using reflection, I could set up tuples of lists

lct = (['top', 'SameAs', self, wxTop, 10],
      ['right', 'SameAs', self, wxRight, 10],
      ['bottom', 'PercentOf', self, wxBottom, 30]
      ['left', 'RightOf', self.panelA, 10])

and use a procedure such as

def constraintFromTuple(items):
    """ every item is a list of length 2 through 5
    the first two are applied via getattr as a function/method call,
    the rest are the arguments to the call.
    retval = wxLayoutConstraints()
    for item in items:
        caller = getattr(getattr(retval,item[0]),item[1])
        if len(item) == 2:
        elif len(item) == 3:
        elif len(item) == 4:
        elif len(item) == 5:
            caller(item[2], item[3], item[4])

    return retval

Your mileage may vary. I found it considerably easier to see what was going on, and generalize the routines.
George Jansen Send private email
Tuesday, June 14, 2005
I just wanted to mention that you can replace those if/elif blocks with a single line by using slicing and the apply syntax:


That will do almost exactly the same thing. (The only important difference is that it will succeed when len(items) > 5 while the original will not.)
Wednesday, June 15, 2005
There are some very important use cases where reflection is essential. Many of these involve software development tools (IDE's, dynamically generated GUIs from XML source, etc). And, in those cases, I'm very glad that the reflection APIs exist.

But in the majority of cases, I think the use of reflection is abused by developers. It makes my blood boil to see objects instantiated at runtime using class names in string objects that have been plucked from properties files and then subjected to various types of transformations (regular expressions, etc). In most of these cases, the functionality of the code has been obfuscated behind a curtain of reflected method calls, and debugging becomes a nightmare. What's worse is that there's usually a non-reflection way of accomplishing the same thing (interfaces).
BenjiSmith Send private email
Wednesday, June 15, 2005

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz