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?)

Of JTables and ScrollPanes

While working on a Swing app today, I came across some interesting code where a class named RowHeader extended JTable.  WTF? In looking at it more closely, it seemed - aha! - they're creating a table to serve as the row header in the JScrollPane.  Makes sense - that way when the table is the viewport of the scroll pane, the column headers don't scroll with the table... just what you want.  I need to do that everywhere.
But wait - it already does that.  How do it know?  My tables don't do that, yet the scroll pane knows to put the row header outside the scroll view port.  Even the simple example here doesn't do anything special to accomplish this task.  I browsed through a bit of the source code to JScrollPane, it must be looking for a JTable instance, but I don't see where right off hand.
So I suspect this is relatively new functionality and the "legacy" code was doing the same thing before Swing did it automatically.

Now, to just get the sorting to show...