Wednesday, December 28, 2005

Emulating static import

It may seem a trivial feature in JDK5, but static import is growing on me. It especially helps me read code to see the flow of method calls without package prefixes.

So at work I'm on a JDK1.4.2 project and miss static import. The solution is quite simple: I put same-named private static methods at the bottom of my class files to emulate the static import, thus:

import javax.swing.UIManager;

/**
 * A toy example: not production code.
 * <p/>
 * Throwing <code>RuntimeException</code> is in poor taste.
 */
public class TopLevel {
    static {
        // Set up font smoothing
        System.setProperty("swing.aatext", "true");

        try {
            setLookAndFeel("net.java.plaf.windows.WindowsLookAndFeel");

        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);

        } catch (final UnsupportedLookAndFeelException e) {
            throw new RuntimeException(e);

        } catch (final InstantiationException e) {
            throw new RuntimeException(e);

        } catch (final ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    // Real work goes here.

    // Simple forwarding to emulate static import:
    private static void setLookAndFeel(final String name)
            throws ClassNotFoundException,
            InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(name);
    }
}

It's not rocket science, but it makes my day just a little bit nicer.

Post a Comment