前提
Java 的匿名类,Lamdba能让我们动态地创造一些我们想要的函数, 有利有弊。
如:
public void function1() {
Cal add = (a, b)->a + b;
log.info("5 + 6 = {}", add.cal(5,6));
log.info("do sth..");
}
public void function2() {
Cal add = (a, b)->a + b;
log.info("1 + 6 = {}", add.cal(1,6));
log.info("do sth..");
}
public void function3() {
Cal add = (a, b)->a + b;
log.info("25 + 26 = {}", add.cal(25,26));
log.info("do sth..");
}
在一个项目中, 可能我们会多次动态构造同1个函数。
如果再用上面的Lambda写法可能不太合适因为重复代码太多。 一旦函数体要被修改可能同时要修改多个地方。
函数引用
这时我们可以在别的类写1个公共函数来代替 Lambda 具体的函数体。
语法:
Interface i = 对象名::函数名
如果该公共函数是静态函数
则语法是
Interface i = 类名::函数名
例子:
下面的乘法类和 加法再平方类就是使用函数引用和静态 函数引用
commonFunc类
@Component
public class CommonCal {
public int mult(int a, int b){
return a*b;
}
}
ExampleFunc1 类
@Component
@Slf4j
public class ExampleFunc1 implements Example {
@Resource
private CommonCal commonCal;
@FunctionalInterface
private interface Cal{
int cal(int a, int b);
}
private static int addAndSquare(int c , int d){
return (c+d) * (c+d);
};
@Override
public void runApp() {
Cal add = (a, b)->a + b;
log.info("5 + 6 = {}", add.cal(5,6));
log.info("do sth..");
Cal mult = commonCal::mult;
log.info("5 * 6 = {}", mult.cal(5,6));
Cal addAndSquare = ExampleFunc1::addAndSquare;
log.info("(5 + 6) * (5 + 6) = {}", addAndSquare.cal(5,6));
}
}
测试结果:
2022-08-28 01:54:22.184 INFO 20668 --- [ main] c.h.j.study.lambda.funcref.ExampleFunc1 : 5 + 6 = 11
2022-08-28 01:54:22.184 INFO 20668 --- [ main] c.h.j.study.lambda.funcref.ExampleFunc1 : do sth..
2022-08-28 01:54:22.185 INFO 20668 --- [ main] c.h.j.study.lambda.funcref.ExampleFunc1 : 5 * 6 = 30
2022-08-28 01:54:22.186 INFO 20668 --- [ main] c.h.j.study.lambda.funcref.ExampleFunc1 : (5 + 6) * (5 + 6) = 121