Friday, March 4, 2011

Reflections on (Java) reflection - isn't there another way?

In general, I am suspicious when I see much use of reflection - especially when creating objects or accessing fields.  It sure seems that there ought to be a better way with a proper object hierarchy.

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:

  1. you would like the window management encapsulated in one class.  
  2. 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?)


Ellie said...
This comment has been removed by a blog administrator.
Thomas Broyer said...

Dependency injection is also a good way of enforcing singletons without resorting to reflection.