javase:构造器引用

/**
 * 1. 构造器引用
 *      和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致
 *      抽象方法的返回值类型即为构造器所属的类的类型
 *
 * 2. 数组引用
 *     数组是一个特殊的类,写法与构造器引用一致
 */
public class ConstructorRefTest {
    /**
     * 构造器引用
     * Supplier中的 T get()
     * Employee的 空参构造器:Employee()
     */
    @Test
    public void test1(){
//        Supplier<Employee> sup = () -> new Employee();
//        System.out.println(sup.get());

        Supplier<Employee> sup = Employee::new;
        System.out.println(sup.get());
    }

    /**
     * Function中的 R apply(T t)
     */
    @Test
    public void test2(){
//        Function<Integer,Employee> func = id -> new Employee(id);
//        Employee employee = func.apply(1001);
//        System.out.println(employee);

        Function<Integer,Employee> func = Employee :: new;
        Employee employee = func.apply(1002);
        System.out.println(employee);
    }

    /**
     * BiFunction中的 R apply(T t,U u)
     */
    @Test
    public void test3(){
//        BiFunction<Integer,String,Employee> func = (id,name) -> new Employee(id,name);
//        System.out.println(func.apply(1001,"Tom"));

        BiFunction<Integer,String,Employee> func = Employee::new;
        System.out.println(func.apply(1002,"Tom"));
    }

    /**
     * 数组引用
     * Function中的 R apply(T t)
     */
    @Test
    public void test4(){
//        Function<Integer,String[]> func = length -> new String[length];
//        String[] arr = func.apply(5);
//        System.out.println(Arrays.toString(arr));

        Function<Integer,String[]> func = String[]::new;
        String[] arr = func.apply(6);
        System.out.println(Arrays.toString(arr));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值