java8中构造器引用与数组引用

1.构造器引用格式:

ClassName::new

2.构造器引用使用要求:

  • 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
  • 抽象方法的返回值类型即为构造器所属的类的类型

3.构造器引用举例:

//构造器引用
//Supplier中的T get()
//Employee的空参构造器:Employee()

   @Test
   public void test1(){

       Supplier<Employee> sup = new Supplier<Employee>() {
           @Override
           public Employee get() {
               return new Employee();
           }
       };
       System.out.println(sup.get());
       System.out.println("*******************");

       Supplier<Employee> sup1 = () -> new Employee();
       System.out.println(sup1.get());
       System.out.println("*******************");

       Supplier<Employee> sup2 = Employee :: new;
       System.out.println(sup2.get());
       System.out.println("*******************");

   }

//Function中的R apply(T t)
//Employee的构造器:Employee(int id)

   @Test
   public void test2(){
       Function<Integer,Employee> fun1 = id -> new Employee(id);
       Employee e = fun1.apply(1001);
       System.out.println(e);

       System.out.println("********************");
       Function<Integer,Employee> fun2 = Employee::new;
       System.out.println(fun2.apply(1002));


   }

//BiFunction中的R apply(T t,U u)
//Employee(int id, String name)

   @Test
   public void test3(){
       BiFunction<Integer,String,Employee> bfun1 = (id,name) -> new Employee(id,name);

       System.out.println(bfun1.apply(1001,"西西"));
       System.out.println("***********************");

       BiFunction<Integer,String,Employee> bfun2 = Employee::new;
       System.out.println(bfun2.apply(1001,"西西"));
}

4.数组引用举例:

数组类型[] :: new
//数组引用
//Function中的R apply(T t)
//new String[int length];

   @Test
   public void test4(){
       Function<Integer,String[]> fun1 = new Function<Integer, String[]>() {
           @Override
           public String[] apply(Integer length) {
               return new String[length];
           }
       };
       String[] fun1String = fun1.apply(5);
       System.out.println(Arrays.toString(fun1String));

       System.out.println("***********************");
       Function<Integer,String[]> fun2 = length -> new String[length];
       String[] fun2String = fun2.apply(5);
       System.out.println(Arrays.toString(fun2String));

       System.out.println("***********************");
       Function<Integer,String[]> fun3 = String[] ::new;
       String[] fun3String = fun3.apply(5);
       System.out.println(Arrays.toString(fun3String));


   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值