目录
一、方法引用概念
使用双冒号 :: 将实例引用或者类名和方法分开
如果编译只有一行的Lambda表达式来调用方法,不妨考虑调用等价的方法引用
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
Lambda表达式写法
Stream.of(1,2,3).forEach(s -> System.out.println(s));
方法引用写法:
Stream.of(1,2,3).forEach(System.out::println);
二、方法引用语法
2.1 引用特定对象的实例方法
object::instanceMethod
引用特定对象的实例方法,如System.out::println
- 创建一个ToUpperCase类
public class ToUpperCase {
public void printString(String str) {
System.out.println(str.toUpperCase());
}
}
- 要使用lambda就需要有一个接口Printable
public interface Printable {
void print(String s);}
- 使用方法引用
public class Demo {
public static void printString(Printable p) {
p.print("hello");
}
public static void main(String[] args) {
// 創建ToUpperCase對象
ToUpperCase obj = new ToUpperCase();
printString(obj::printString);
}
}
2.2通过类名引用静态成员方法
Class::staticMethod
引用静态方法,如Math::abs
前提:类和静态成员方法已经存在
- 定义一个接口
public interface Cacable {
int calAbs(int number);}
- 使用方法引用
public class Demo {
public static int method(int number,Cacable c) {
return c.calAbs(number);
}
public static void main(String[] args) {
int number = method(-10, Math::abs);
System.out.println(number);}
2.3 Super引用父类成员方法
- 创建Greetable接口
public interface Greetable {
void greet();}
- 父类
public class Human {
public void syaHello() {
System.out.println("hello human");
}}
- 子类
public class Man extends Human{
// 重寫sayHello
@Override
public void sayHello() {
System.out.println("hello man");
}
// 。定義一個方法參數傳遞Greetable接口
public void method(Greetable g) {
g.greet();
}
public void show() {
method(() -> {
// 創建父類對象
Human human = new Human();
human.sayHello();
});
// 因為游資弗雷,所以存在一個關鍵字super,我們可以直接使用super調用父類的成員方法
method(() -> {
// 創建父類對象
super.sayHello();
});
// 方法引用
method(super::sayHello);
}
public static void main(String[] args) {
new Man().show();
}}
2.4 通过this引用本类成员方法
public void buy() {
System.out.println("buy house");
}// 。定義一個方法參數傳遞Greetable接口
public void method(Greetable g) {
g.greet();
}
public void show() {
method(this::buy);
}
public static void main(String[] args) {
new Man().show();
}
2.5 构造方法的引用
printName(name,Person::new)