Java idiom for lambdas with non-SAM interfaces

In Brian Goetz’ answer to the other question, he suggested using static factory methods. In this case it’s a bit tedious, since WindowListener defines seven handler methods, so you’d need to define seven static factory methods. This isn’t that bad, though, since there is already a WindowAdapter class that provides empty implementations of all of the methods. (If there isn’t one, you’d have to define your own equivalent.) Here’s how I’d do it:

class WLFactory {
    public static WindowListener windowOpened(Consumer<WindowEvent> c) {
        return new WindowAdapter() {
            @Override public void windowOpened(WindowEvent e) { c.accept(e); }
        };
    }

    public static WindowListener windowClosing(Consumer<WindowEvent> c) {
        return new WindowAdapter() {
            @Override public void windowClosing(WindowEvent e) { c.accept(e); }
        };
    }

    // ...
}

(The other 253 cases are analogous.)

Each factory method creates a subclass of WindowAdapter that overrides the appropriate method to call the lambda expression that’s passed in. No need for additional adapter or bridge classes.

It would be used as follows:

window.addWindowListener(WLFactory.windowOpened(we -> System.out.println("opened")));

Leave a Comment