Lambda方法的引用可以參考 https://www.cnblogs.com/happyflyingpig/p/9004534.html 中的示例三,接下來討論一下構造函數的方法引用
java8給我們提供了 Supplier<T> 、Function<T,R>、BiFunction<T,U,R>等函數式接口(就是interface中只有一個抽象函數的接口),我們可以利用這幾個函數式接口來創建構造函數的方法引用。
一、先准備一個類,這個類有無慘構造函數、一個參數的構造函數、兩個參數多的構造函數
public class Apple { private int weight; private String color; public Apple(){} public Apple(int weight) { this.weight = weight; } public Apple(int weight, String color) { this.weight = weight; this.color = color; } setters();&getters();&toString(); }
二、當構造函數是無參數的時候
/**
* 假設構造函數沒有參數 它適合Supplier簽名
*/
Supplier<Apple> supplier1 = Apple::new; // 構造函數引用指向默認的Apple()構造函數
supplier1.get(); //調用get方法將產生一個新的Apple
//這兩個等價 Supplier<Apple> supplier2 = () -> new Apple(); supplier2.get();
三、當構造函數是有一個參數的時候
/** * 如果構造函數簽名是Apple(Integer weight), 也就是構造函數只有一個參數, 那么他就適合Function接口的簽名 */ Function<Integer, Apple> function1 = Apple::new; //指向Apple(Integer weight)的構造函數引用 Apple apple1 = function1.apply(150); //調用該Function函數的apply方法,產生一個Apple //等價於 Function<Integer, Apple> function2 = (weight) -> new Apple(weight); Apple apple2 = function2.apply(200);
簡單的一個應用
List<Integer> integerList = Arrays.asList(4, 5, 6, 7, 8); getAppleList(integerList, Apple::new); public static List<Apple> getAppleList(List<Integer> list, Function<Integer, Apple> function) { List<Apple> result = new ArrayList<>(); for (Integer it : list) { Apple apple = function.apply(it); result.add(apple); } return result; }
四、當構造函數是有兩個參數的時候
/** * 如果構造函數簽名是Apple(Integer weibht, String color), 也就是構造函數有兩個參數,那么就適合BiFunction接口的簽名 */ BiFunction<Integer, String, Apple> biFunction1 = Apple::new; biFunction1.apply(100, "紅色"); //等價於 BiFunction<Integer, String, Apple> biFunction2 = (weight, color) -> new Apple(weight, color); biFunction2.apply(100, "紅色");
簡單應用
/** * 應用,根據上面學習的例子,我們可以不用實例化來引用它 */ Map<String, Function<Integer, Fruit>> fruitMaps = new HashMap<>(20); fruitMaps.put("banner", Banner::new); fruitMaps.put("pear", Pear::new); //獲取水果對象 Fruit banner = fruitMaps.get("banner").apply(10); Fruit pear = fruitMaps.get("pear").apply(20); System.out.println(banner); System.out.println(pear);
參考:
【1】《Java8實戰》