本文參考: 《30分鐘入門Java8之方法引用》
方法引用,一般有四種形式:
引用構(gòu)造方法
ClassName::new
等價于Lamda表達(dá)式
()->new ClassName()
函數(shù)接口
interface F{
ClassName contructMethod();
}
引用靜態(tài)方法
ClassName::staticMethod
等價于Lamda表達(dá)式:
(a1,a2,...,an)->ClassName.staticMethod(a1,a2,...,an);
函數(shù)接口
interface F{
ReturnType method(a1,a2,....,an);
}
引用對象的實(shí)例方法
obj::method
等價于Lamda表達(dá)式:
(a1,a2,....,an)->obj.method(a1,a2,...,an)
函數(shù)接口
interface F{
ReturnType method(a1,a2,....,an);
}
引用類型對象的實(shí)例方法(※)
ClassType::method
等價于Lamda表達(dá)式:
(obj,a1,a2,....,an)->obj.method(a1,a2,...,an)
其中沸久,obj是ClassType類型的對象坛缕。
函數(shù)接口
interface F{
ReturnType method(a1,a2,....,an);
}
比如,有類Int胡诗,它保存一個int值邓线,并且有一個減兩個減數(shù)的方法subtract
class Int{
int value;
public Int(int value) {
this.value = value;
}
int subtract(Int other1,Int other2){
return value-other1.value-other2.value;
}
}
還有一個Func接口淌友,接受三個Int參數(shù),返回一個int值
interface Func{
int action(Int a,Int b,Int c);
}
在Test中有方法show
public static void show(Int a,Int b,Int c,Func func){
System.out.print(func.action(a,b,c));
}
那么骇陈,可以按如下方式使用show:
Int intA=new Int(1),intB=new Int(2),intC=new Int(3);
show(intA,intB,intC,/*Lamda表達(dá)式*/(Int a,Int b,Int c)->a.subtract(b,c));
show(intA,intB,intC,/*引用類型對象的實(shí)例方法*/Int::subtract);