本文将介绍lambda表达式的几种方法引用:静态方法引用、非静态方法引用、构造函数引用。较为特殊的对象方法引用留到下一篇博客来说明。
public class Test {
//为了展示方便,将函数式接口写于同一类中
@FunctionalInterface
public interface Calculate {
int calculate(int a, int b);
}
public static void main(String[] args) {
Calculate calculate = (x, y)->{
if(x > y){
return x - y;
}else if(x < y){
return y - x;
}else{
return 0;
}
};
}
}
在上面这个例子中,如果涉及到比较复杂的接口实现逻辑的时候,会使得我们的代码看起来较为繁琐,因此,我们可以利用方法调用来简化代码。
静态方法引用
public class Test {
//为了展示方便,将函数式接口,静态方法写于同一个类中
@FunctionalInterface
public interface Calculate {
int calculate(int a, int b);
}
public static void main(String[] args) {
Calculate calculate = Test::calculate;
}
//要调用的静态方法
private static int calculate(int x, int y){
if(x > y){
return x - y;
}else if(x < y){
return y - x;
}else{
return 0;
}
}
}
我们使用类名::静态方法调用一个静态方法来进行接口的实现,前提是:该静态方法参数和返回值与函数式接口中的参数和返回值相同。
非静态方法引用
public class Test {
@FunctionalInterface
public interface Calculate {
int calculate(int a, int b);
}
public static void main(String[] args) {
Calculate calculate = new Test()::calculate;
}
//要调用的非静态方法
private int calculate(int x, int y) {
if (x > y) {
return x - y;
} else if (x < y) {
return y - x;
} else {
return 0;
}
}
}
我们使用new 类名( )::非静态方法调用一个非静态方法来进行接口的实现,前提是:该非静态方法参数和返回值与函数式接口中的参数和返回值相同。
构造方法引用
public class Test {
//为展示方便编写内部类
private static class Calculate{
public Calculate(){
System.out.println("调用构造方法");
}
public Calculate(String s1){
System.out.println("调用构造方法" + s1);
}
public Calculate(String s1, String s2){
System.out.println("调用构造方法" + s1 + s2);
}
}
@FunctionalInterface
public interface GetCalculateNone {
Calculate getCalculate();
}
@FunctionalInterface
public interface GetCalculateSingle {
Calculate getCalculate(String a);
}
@FunctionalInterface
public interface GetCalculate {
Calculate getCalculate(String a, String b);
}
public static void main(String[] args) {
GetCalculateNone getCalculateNone = Calculate::new;
GetCalculateSingle getCalculateSingle = Calculate::new;
GetCalculate getCalculate = Calculate::new;
}
}
使用类名::new能够根据该函数式接口需要的参数自动到所给类中查找是否有构造参数可对应。