In any case, I came across an interesting use case. In this GUI application, the requirement is to create only one window of any given type. So the class is passed into a window manager class. It looks up in its table to see if one has been created and if not, creates one. It does this by being passed the class of the window to create and uses reflection to instantiate it.
There are a couple valid justifications for this:
- you would like the window management encapsulated in one class.
- you would like to not instantiate one if one already exists. Using reflection enables this without having to resort to multiple method calls (although it wouldn't be the end of the world).
The other option would be for every window class to implement a singleton pattern.
Isn't there another way?
In fact, the benefits of Scala come to mind. All you would need is to pass a bit of code to the window manager which it would execute to create the window in lieu of finding the constructor from reflection on the class definition.
Or, in JDK 7 terms, pass in a closure (from what I've heard of the various proposals).
One could also emulate this with a one-method interface. Having written all this, it seems it might be useful for each window to implement a singleton pattern, especially if there are various places where the window is being created. But, that might be a bad sign in its own right.
BTW - why do I not like reflection? Primarily because I tend to use the "Find References" feature of my IDE-of-the-project. And it doesn't catch uses of reflection. (N.B. does FindBugs?)