函数式编程 - 方法参考
方法引用有助于通过名称指向方法。使用“::”符号描述方法引用。方法引用可用于指向以下类型的方法 -
静态方法- 静态方法可以使用 ClassName::Method 名称表示法进行引用。
//Method Reference - Static way Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;
实例方法- 可以使用 Object::Method 名称表示法来引用实例方法。
//Method Reference - Instance way Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;
以下示例显示了方法引用在 Java 8 及以上版本中的工作原理。
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); } }
输出
Vehicle[Hyundai, Verna, 2018] Vehicle[Tata, Harrier, 2019]