方法引用符号
双冒号:: 也被归置为引用运算符,
使用方法引用的使用场景
通过对象名引用成员方法
// 先准备一个类,类中需要定义一个成员方法
public class Demo02Method {
// 定义一个成员方法,传递一个字符串,把字符串转换为大写输出
public void pringUpperCaseString(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
* 对象已经是存在的method
* 成员方法也是已经存在的pringUpperCaseString
* 所以我们就可以使用对象名来引用成员方法
*/
//首先必须是对象已经存在
Demo02Method method = new Demo02Method();
printString(method::pringUpperCaseString);// HELLO WORLD
}
}
通过类名引用静态方法
比如:java.lang.Math
类中存放的都是静态方法
// 定义一个函数式接口
@FunctionalInterface
public interface Demo01MathStaticMethod {
// 定义一个抽象方法
double calculateAbs(double d);
}
// 定义一个测试类
public class Dem02MethodStatic {
// 定义一个静态方法,该方法中传递一个函数式接口,再次传递一个浮点数
public static double calc(double d,Demo01MathStaticMethod math) {
return math.calculateAbs(d);
}
public static void main(String[] args) {
// 传统的Lambda表达式写法
double num = calc(-3.14, (d) -> {
return Math.abs(d);
});
System.out.println(num);// 3.14
/*
* 使用方法引用进行优化Lambda
* 首先类名已经确定的
* 类中定义的静态方法是已经确定的
* 使用类名引用类中的静态方法
*/
double d = calc(-3.14, Math::abs);
System.out.println(d);// 3.14
}
}
备注:
Lambda表达式写法:
d -> Math.abs(d)
方法引用写法:
Math::abs
这两种写法是等价的。
通过super来引用成员方法
如果存在继承关系,当Lambda中需要使用super调用时,也可以使用方法引用来优化Lambda表达式。
// 定义一个父类
public class Animal {
// 定义一个成员方法 交流的方法
public void talk() {
System.out.println("hello 我是一只动物!");
}
}
// 定义一个函数式接口
@FunctionalInterface
public interface Meet {
// 定义一个抽象方法 见面的方法
void meet();
}
// 定义一个子类
public class Cat extends Animal{
@Override
public void talk() {
System.out.println("hello 我是一只猫!");
}
// 定义一个方法 方法的参数传递一个函数式接口Meet
public void meet(Meet m){
m.meet();
}
// 定义一个成员方法 沟通的方法
public void commun() {
// 传统的Lambda表达式写法
meet(() -> {
// 创建父类的对象
// 调用父类的方法
Animal animal = new Animal();
animal.talk();
});
// 使用父类当中的方法 直接用super来调用
meet(() -> super.talk());
/*
* 使用super关键字来引用成员方法
* super已经存在的
* 父类当中的成员方法talk已经存在的
* 可以使用super引用父类当中的成员方法
*
*/
// 优化的结果
meet(super::talk);
}
public static void main(String[] args) {
new Cat().commun();
}
}
通过this来引用本类当中的成员方法
this指代当前对象,如果需要引用的方法就是本类当中的成员方法,那么可以使用this::成员方法格式来优化Lambda表达式
@FunctionalInterface
public interface Study {
// 定义一个学习的抽象方法
void study();
}
// 定义一个学生类
public class Student {
// 定义一个成员方法,方法的参数传递一个函数式接口Study
public void study(Study s) {
s.study();
}
// 定义一个work方法
public void work() {
System.out.println("我学习我快乐!");
}
// 定义一个成员方法快乐的方法
public void toHappy() {
// 传统的Lambda表达式
study(() -> {
// 创建对象
Student student = new Student();
student.work();
});
// 使用this关键字优化Lambda
//study(s);
//Student student = new Student();
study(this::work);
}
public static void main(String[] args) {
new Student().toHappy();
}
}