java遺珠之lambda與方法過載
版權宣告:本文為博主原創文章,未經博主允許不得轉載。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")); } }
- 與介面中的引數列表有關,當引數列表不一樣時就可以知道呼叫哪個方法,lambda對應哪個介面了
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")); } }