本篇内容
方法引用
备注:使用方法引用优化Lambda表达式,
1.对象必须是已经存在的method
2.成员方法也是已经存在的printString
所以就可以适用对象名来引用成员方法
在测试类中,定义一个静态方法,静态方法传递一个函数式接口Printable,函数式接口当中定义了唯一一个抽象方法print,这个print方法接收一个字符串参数,目的就是为了打印接收的字符串参数,通常我们可以使用Lambda表达式实现以上需求。但是经过我们观察,对字符串进行控制台打印输出的查找方案,明明已经有了现成的执行方案,System.out.对象中有一个方法println(String str),所以我们可以直接通过对象名来引用该方法,在控制台打印输出字符串内容。
//打印流对象确定
PrintStream printStream = System.out;
//通过对象名来引用对应的方法
printString(printStream::println); //Hello world
其中的双冒号::
被称之为方法引用
,是一种新语法。
方法引用符号
双冒号::
,也被归置为引用运算符。
方法引用的使用场景
1.通过对象名引用成员方法
//先准备一个类,类中需要定义一个成员方法
public class Demo02Method {
//定义一个成员方法,传递一个字符串,把字符串转换为大写输出
public void printString(String str) {
System.out.println(str.toUpperCase());
}
}
//准备一个函数式方法
@FunctionalInterface
public interface Printable {
//定义一个唯一的抽象方法
public abstract void print(String str);
}
//准备测试类
public class Demo01Method {
//定义静态方法,传一个函数式接口
public static void printString(Printable p) {
p.print("Hello World");
}
public static void main(String[] args) {
//传统的Lambda表达式写法
printString((String str) ->{
System.out.println(str.toUpperCase()); //HELLO WORLD
Demo02Method method = new Demo02Method();
method.printString(str); //HELLO WORLD
});
//打印流对象确定
PrintStream printStream = System.out;
//通过对象名来引用对应的方法
printString(printStream::println); //Hello world
/*
* 使用方法引用优化Lambda表达式
* 1.对象必须是已经存在的method
* 2.成员方法也是已经存在的printString
* 所以我们就可以使用对象名来引用成员方法
*/
//首先必须是对象已经存在
Demo02Method method = new Demo02Method(