Java reflection appropriateness

Posted by jsn on Stack Overflow See other posts from Stack Overflow or by jsn
Published on 2010-05-15T18:45:50Z Indexed on 2010/05/15 18:54 UTC
Read the original article Hit count: 241

Filed under:
|

This may be a fairly subjective question, but maybe not. My application contains a bunch of forms that are displayed to the user at different times. Each form is a class of its own. Typically the user clicks a button, which launches a new form.

I have a convenience function that builds these buttons, you call it like this:

buildButton( "button text", new SelectionAdapter() {
     @Override
     public void widgetSelected( SelectionEvent e ) {
        showForm( new TasksForm( args... ) );
     }
  } );

I do this dozens of times, and it's really cumbersome having to make a SelectionAdapter every time.

Really all I need for the button to know is what class to instantiate when it's clicked and what arguments to give the constructor, so I built a function that I call like this instead:

buildButton( "button text", TasksForm.class, args... );

Where args is an arbitrary list of objects that you could use to instantiate TasksForm normally.

It uses reflection to get a constructor from the class, match the argument list, and build an instance when it needs to. Most of the time I don't have to pass any arguments to the constructor at all. The downside is obviously that if I'm passing a bad set of arguments, it can't detect that at compilation time, so if it fails, a dialog is displayed at runtime. But it won't normally fail, and it'll be easy to debug if it does.

I think this is much cleaner because I come from languages where the use of function and class literals is pretty common. But if you're a normal Java programmer, would seeing this freak you out, or would you appreciate not having to scan a zillion SelectionAdapters?

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection