Tuesday, December 27, 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.

2 comments:

Anonymous said...

This is exactly why people didn't want static imports. What have you saved, ten letters ("UIManager.")? How many times do you call "setLookAndFeel"? Once? It's meant for *repetitive* symbol accesses, like Math.this(Math.THAT + Math.whatever) * Math.somethingElse(), and it's not even really meant for that, either.
I hope the people reading your blog don't do what you've done.
See http://java.sun.com/docs/books/tutorial/java/interpack/staticimport.html
"Note: Use static import very sparingly, if at all. It's useful for situations when you need frequent access to a few static objects from one or two classes. Overusing static import can result in code that is difficult to read and maintain, because readers of the code won't know which class defines a particular static object. Used properly, static import makes code more readable by removing class name repetition."

Brian Oxley said...

I'm sorry, Anonymous, you feel that way. I consider it a matter of taste, not a religious issue. If you do not like static import, do not use it. I hope it does not bother you over much.

And why save 10 characters? Because it is an example. A lengthy class where the improvement in readability is significant is too long to post in a blog entry.