【Java】lambda的方法引用

       本文将介绍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能够根据该函数式接口需要的参数自动到所给类中查找是否有构造参数可对应

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值