新特性02| 方法引用

简介

Method references provide easy-to-read lambda expressions for methods that already have a name.

(译文)方法引用为已有名字的方法提供了简单易读的lambda表达式写法。

说明

方法引用通过方法的名字指向一个方法,可使得减少冗余代码,使其更加紧凑简洁。

语法

使用一对冒号::

简单用法举例

利用下方代码解释Java8支持的4中方法引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// java8中已包含
@FunctionalInterface
public interface Supplier<T> {
T get();
}

class Car {
//Supplier是jdk1.8的接口,这里和lamda一起使用了
public static Car create(final Supplier<Car> supplier) {
return supplier.get();
}

public static void collide(final Car car) {
System.out.println("Collided " + car.toString());
}

public void repair() {
System.out.println("Repaired " + this.toString());
}

public void follow(final Car another) {
System.out.println("Following the " + another.toString());
}
}
  1. 构造器引用,语法:Class::new,或Class<T>::new

    • 举例:
      1
      2
      final Car car = Car.create(Car::new); //构造出一个car对象
      final List<Car> cars = Arrays.asList(car); //利用car构建了一个List
  2. 静态方法引用,语法:Class::static_method

    • 举例:
      1
      cars.forEach(Car::collide); //打印出了Collided package.Car@HexStringofHashcode
  3. 特定类的任意对象方法引用,语法:Class::method

    • 举例:
      1
      cars.forEach(Car::repair); //打印出了Repaired package.Car@HexStringofHashcode
  4. 特定对象方法引用,语法:instance::method

    • 举例:
      1
      2
      final Car police = Car.create(Car::new); //同1的构造器引用
      cars.forEach(police::follow); //打印出了Following the package.Car@HexStringofHashcode

方法引用实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Java8Tester {
public static void main(String[] args) {
List names = new ArrayList();

names.add("Google");
names.add("Runoob");
names.add("Taobao");
names.add("Baidu");
names.add("Sina");

names.forEach(System.out::println);
}
}
```
**输出:**
```Text
Google
Runoob
Taobao
Baidu
Sina

注意:
由于System.out的定义为public final static PrintStream out = null;,而println的源码为:

1
2
3
4
5
6
7
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}

所以可确定上面代码中使用的是特定类的任意对象方法引用


更多详细内容参见官方文档

码哥 wechat
欢迎关注个人订阅号:「码上行动GO」