# Java8之构造引用和数组引用 **Repository Path**: fpfgitmy_admin/java8-structure-arr ## Basic Information - **Project Name**: Java8之构造引用和数组引用 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-04-28 - **Last Updated**: 2021-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 构造器引用 + 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致 + 抽象方法的返回值类型即为构造器所属的类的类型 + 格式: 类 :: new; #### 空参构造方法 ``` // Supplier中的 T get() // Goods中的空参构造器 @Test public void test1() { Supplier s1 = new Supplier() { @Override public Goods get() { return new Goods(); } }; Goods goods = s1.get(); System.out.println("原始写法" + goods.toString()); System.out.println("-------------------------"); Supplier s2 = () -> new Goods(); Goods goods1 = s2.get(); System.out.println("使用Lambad写法" + goods1.toString()); Supplier s3 = Goods::new; Goods goods2 = s3.get(); System.out.println("使用空参构造器引用的写法" + goods2.toString()); } ``` #### 一个参数的构造方法 ``` // Function 中的 apply(T t) @Test public void test2() { Function f1 = d1 -> new Goods(d1); Goods apply = f1.apply(1.4); System.out.println("使用Lambda写法" + apply.toString()); System.out.println("-------------------------"); // 由于Function的第一个泛型参数指定了,所以调用的是Goods(Double price)的构造方法 Function f2 = Goods::new; Goods apply1 = f2.apply(1.5); System.out.println("使用带参构造器引用的写法" + apply1.toString()); } ``` #### 多个参数的构造方法 ``` // BiFunction中的 R apply(T t,U u,R r) @Test public void test3() { BiFunction b1 = (s1, d1) -> new Goods(s1, d1); Goods g1 = b1.apply("小米", 12.3); System.out.println("使用了Lambda的写法" + g1.toString()); System.out.println("-------------------------"); // BiFunction的第一个泛型为参数1,第二个泛型为参数2 BiFunction b2 = Goods::new; Goods g2 = b2.apply("小米", 12.4); System.out.println("使用了带参构造器引用的写法" + g2.toString()); } ``` ### 数组引用 + 把数组当做是一个类,和构造器引用类似 ``` @Test public void test4() { Function f1 = l -> new String[l]; String[] apply = f1.apply(5); System.out.println("使用了Lambda表达式的写法" + apply.length); Function f2 = String[] ::new; String[] apply1 = f2.apply(10); System.out.println("使用了数组引用的写法" + apply1.length); } ```