java8給咱們提供了 Supplier<T> 、Function<T,R>、BiFunction<T,U,R>等函數式接口(就是interface中只有一個抽象函數的接口),咱們能夠利用這幾個函數式接口來建立構造函數的方法引用。html
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);
簡單的一個應用java
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, "紅色");
簡單應用app
/** * 應用,根據上面學習的例子,咱們能夠不用實例化來引用它 */ 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實戰》函數