Functional Programming With Java 简明教程
Functional Programming - Method References
方法引用有助于按方法的名称指向方法。使用“::”符号来描述方法引用。方法引用可用于指向以下类型的:
Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
-
Static methods - static method can be reference using ClassName::Method name notation.
//Method Reference - Static way
Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;
-
Instance methods - instance method can be reference using Object::Method name notation.
//Method Reference - Instance way
Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;
以下示例展示了从 Java 8 开始,方法引用在 Java 中的工作原理。
Following example shows how Method references works in Java 8 onwards.
interface Factory {
Vehicle prepare(String make, String model, int year);
}
class Vehicle {
private String make;
private String model;
private int year;
Vehicle(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
public String toString(){
return "Vehicle[" + make +", " + model + ", " + year+ "]";
}
}
class VehicleFactory {
static Vehicle prepareVehicleInStaticMode(String make, String model, int year){
return new Vehicle(make, model, year);
}
Vehicle prepareVehicle(String make, String model, int year){
return new Vehicle(make, model, year);
}
}
public class FunctionTester {
public static void main(String[] args) {
//Method Reference - Static way
Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;
Vehicle carHyundai = vehicle_factory_static.prepare("Hyundai", "Verna", 2018);
System.out.println(carHyundai);
//Method Reference - Instance way
Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;
Vehicle carTata = vehicle_factory_instance.prepare("Tata", "Harrier", 2019);
System.out.println(carTata);
}
}