Lambda 表达式
Lambda 与内部类 JDK 8 之前,要把「一段逻辑」当作参数传给方法,常见写法是匿名内部类——创建一个没有名字的类,并实现目标接口。Lambda 表达式针对其中最常见的一类场景做了简化:目标类型是函数式接口(通过 SAM 判定的接口)时,可以用 (参数) -> 表达式 代替整个匿名类。 同一件事,两种写法 以 Runnable 为例: // Runnable is an interface (not a class); SAM: single abstract method void run() // Left: Runnable r1 — variable type is the interface // Right: new Runnable() { ... } — not "new interface"; defines an anonymous class // that implements Runnable and overrides run(); compiler emits EnclosingClass$1.class Runnable r1 = new Runnable() { @Override public void run() { System.out.println("hello"); } }; // JDK 8 lambda; target type is still Runnable (functional interface) // Semantically same as the anonymous class above; often compiled via invokedynamic Runnable r2 = () -> System.out.println("hello"); 以 Comparator 为例(同样是「接口 + 匿名实现类」): ...