版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82807255
当lambda的目标类型不是很明确时,就需要根据一些特征来判断lambda的目标类型,比较常见的就是在方法重载的时候。
public class OverloadLambda { interface Runable { void run(); } interface Runable2 { void run1(); } void methodA(Runable runable) { runable.run(); } void methodA(Runable2 runable2) { runable2.run1(); } public static void main(String[] args) { new OverloadLambda().methodA(() -> System.out.println("methodA")); } }
public class OverloadLambda { interface Runable { void run(); } interface Runable2 { void run(int x); } void methodA(Runable runable) { runable.run(); } void methodA(Runable2 runable2) { runable2.run(10); } public static void main(String[] args) { new OverloadLambda().methodA(() -> System.out.println("methodA")); new OverloadLambda().methodA((x) -> System.out.println("methodA"+x)); } }
public class OverloadLambda { interface Runable { void run(); } interface Runable2 { String run(); } void methodA(Runable runable) { runable.run(); } String methodA(Runable2 runable2) { return runable2.run(); } public static void main(String[] args) { OverloadLambda overloadLambda = new OverloadLambda(); overloadLambda.methodA(() -> System.out.println("methodA")); System.out.println(overloadLambda.methodA(() -> "methodA return string")); } }