lambda和方法引用之间有一个关键的区别:Lambda 是惰性的,它们只会在调用方法时调用类构造函数。另一方面,对于方法引用,构造函数只会在分配了方法引用的地方被立即调用,而不是在方法调用时调用。
public class MethodReferenceVSLambdaChallenge { public static void main(String... doYourBest) { Runnable universeImpactRunnable = () -> new ChuckNorris().roundHouseKick(); Runnable galaxyImpactRunnable = new ChuckNorris()::roundHouseKick; System.out.print("The galaxy is finished = "); universeImpactRunnable.run(); universeImpactRunnable.run(); galaxyImpactRunnable.run(); galaxyImpactRunnable.run(); } static class ChuckNorris { private static int numberOfKicks; private int galaxyDamage; ChuckNorris() { this.galaxyDamage = numberOfKicks++; } void roundHouseKick() { System.out.print(this.galaxyDamage); } } } |
结果: A) The galaxy is finished = 1234 B) The galaxy is finished = 0123 C) The galaxy is finished = 0100 D) The galaxy is finished = 1200
在下面这行并没有调用构造函数:
Runnable universeImpactRunnable = () -> new ChuckNorris().roundHouseKick(); |
Runnable galaxyImpactRunnable = new ChuckNorris()::roundHouseKick; |
universeImpactRunnable.run(); universeImpactRunnable.run(); |
当我们调用这些方法时:值将为 0,因为请记住,构造函数只会被调用一个,并且在方法引用声明的那一刻它已经被调用了。