五.方法引用
方法引用使得开发者可以直接引用现存的方法、Java类的构造方法或者实例对象。方法引用和Lambda表达式配合使用,使得java类的构造方法看起来紧凑而简洁,没有很多复杂的模板代码。
语法:
如果是静态方法,则是ClassName::methodName。如 Object ::equals
如果是实例方法,则是Instance::methodName。如Object obj=new Object();obj::equals;
构造函数.则是ClassName::new
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package com.ehking.example.java8.newfeature.demo05;
import java.util.function.Supplier;
public class Car {
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 follow(final Car another) { System.out.println("Following the " + another.toString()); }
public void repair() { System.out.println("Repaired " + this.toString()); }
}
|
引用的car测试例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.ehking.example.java8.newfeature.demo05;
import java.util.Arrays;
public class Java8MethodRef {
public static void main(String[] args) {
final Car car = Car.create(Car::new); final List<Car> cars = Arrays.asList(car);
cars.forEach(Car::collide);
cars.forEach(Car::repair);
final Car police = Car.create(Car::new); cars.forEach(police::follow);
}
}
|