Lambda 构造方法引用 -- 类名::new

5 篇文章 0 订阅

上一篇文章
https://blog.csdn.net/nvd11/article/details/126565044?spm=1001.2014.3001.5502
介绍了Lambda的函数引用

但是如果这个方法是某个类的构造函数。
那么还有1个新的写法
类名::new

例子:

Cat 类

package com.home.javacommon.study.lambda;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Cat {
    
    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

}

注意, 由于Lombok 的@Data 注解, 这个类实际上已经实现了无参构造方法和重写了ToString()方法

ExampleConstruct1 类

@Component
@Slf4j
public class ExampleConstruct1 implements Example {

    @FunctionalInterface
    private interface CatServiceNoArgs{
       Cat getCat();
    }

	@FunctionalInterface
    private interface CatService{
        Cat getCat(String name, int age);
    }

    @Override
    public void runApp() {
        CatServiceNoArgs catService1 = ()->new Cat();
        CatServiceNoArgs catService2=Cat::new;

        log.info(catService1.getCat().toString());
        log.info(catService2.getCat().toString());

        CatService catService3 = (name, age)->new Cat(name, age);
        CatService catService4=Cat::new;

        log.info(catService3.getCat("Alice", 3).toString());
        log.info(catService4.getCat("Bill", 4).toString());
    }
}

这里我们创建了两个接口
CatServiceNoArgs
CatService
1个是无参的接口函数, 1个是有参的

对于无参接口

CatServiceNoArgs catService1 = ()->new Cat();
CatServiceNoArgs catService2=Cat::new;

上面两行是等效的

对于另1个有参接口
lambok任然可以简写为:
CatServiceNoArgs catService2=Cat::new;

不需要指明参数

使用接口函数把参数输入就ok
log.info(catService4.getCat(“Bill”, 4).toString());

至于为什么不直接调用类构造函数?
Cat1 = new Cat(“bill”, 4)

这就涉及设计模式和编程思维了, 很多时候我们并不想把类暴露给下游的类。
大家可以学习下面向接口编程的思想, 这里就不展开了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nvd11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值