How can I write an anonymous function in Java?

后端 未结 5 1159
无人及你
无人及你 2020-12-22 23:15

Is it even possible?

5条回答
  •  隐瞒了意图╮
    2020-12-23 00:05

    Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

    A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

    private static String pretty(Node node) {
        return "Node: " + new Object() {
            String print(Node cur) {
                return cur.isTerminal() ?
                    cur.name() :
                    ("("+print(cur.left())+":"+print(cur.right())+")");
            }
        }.print(node);
    }
    

    (I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

提交回复
热议问题