上一篇文章
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)
这就涉及设计模式和编程思维了, 很多时候我们并不想把类暴露给下游的类。
大家可以学习下面向接口编程的思想, 这里就不展开了。