面向对象的编程中,程序执行期间方法不能作为值相互传递,而是二等公民。必须依赖对象或者类调用。
方法作为值相互传递,构成了java8的基本思想:如stream,stream接收的参数可能只是一个方法f(),而不需要 实例.f()
lamda表达式和函数式接口绑定
// 定义一个函数式接口
Interface FunctionInterface {
boolean do(Apple apple);
}
// 定义functionInterface函数参数化的方法fun
boolan fun(FunctionInterface functionInterface){
Apple apple = new Apple();
return functionInterface.do(apple);
}
lamda 的表达式只需要指定满足:(1)返回值是相同,都是boolean(2)参数是数目、类型、顺序相同,一个,都是String
fun((String s) -> bean);
如何构建一个方法引用?使用 ::符号,和lamda表达式是的等价的,都是传入行为参数
// 函数式接口
Interface FunctionInterface {
boolean do(Apple apple, String s);
}
class AtherClass{
// 静态方法,参数、返回值和函数式接口相同
public static boolean xxx(Apple a, String s){
retrun true;
}
// 实例方法,参数、返回值和函数式接口相同
public boolean yyy(Apple a, String s){
return true;
}
}
class Apple {
// 实例方法 ,返回值和函数式接口相同,参数和函数接口第二个参数相同,本类和第一个参数相同
public boolean zzz(String s){
retrun true;
}
}
在类的静态方法或者实例方法 和 函数式接口的方法的参数、返回值都相同的前提下(第三种情况除外),创建函数引用分为三种
(1)类AtherClass的静态方法,类名::静态方法
FunctionInterface functionInterface = AtherClass::xxx
(2)类AtherClass的实例方法,实例引用::实例方法
AtherClass atherClass = new AtherClass();
FunctionInterface functionInterface = atherClass ::yyy
(3)特别的!实例类Apple是恰好是函数式接口方法的第一参数, 类名::实例方法
FunctionInterface functionInterface = Apple::zzz
所以当函数式接口第一参数是泛型时,实例方法都可以以Apple::xxx形式
Interface Interface<T>{
beoolean do(T t, String s)
}
使用Interface作为参数,定义方法fun时候,都要绑定T
void fun(Interface<Apple> interface){
。。。
}
传入函数引用实例方法
fun(Apple::xxx)