Friday, February 10, 2006

A JNLP API convenience method

I am working with the JNLP API at the moment, and I find myself constantly using ServiceManager.lookup(String) and the painful call with a string (have you seen my typing?) and casting of the return.

Since I am fortunate to be using JDK5 on this project, I created a convenience method for this purpose:

  1 private static <T> T lookup(final Class<T> clazz) {
  2     final String className = clazz.getName();
  3 
  4     try {
  5         return (T) ServiceManager.lookup(className);
  6 
  7     } catch (final UnavailableServiceException e) {
  8         final String message = "No JNLP service: "
  9                 + className;
 10 
 11         showMessageDialog(null, message,
 12                 "WebStart Error", ERROR_MESSAGE);
 13 
 14         throw new IllegalStateException(message, e);
 15     }
 16 }
 17 

There are two advantages to this technique.

First, I can replace all my calls using strings and casts to just this: final BasicService basicService = lookup(BasicService.class);.

Second, I can lose the try { /* lookup */ } catch (final UnavailableServiceException e) { /* Handle exception */ } blocks anytime I use a service, and trade them for helpful dialogs with the user.

No comments: