Java 8 方法引用

四种类型的方法引用

类型语法对应的lamabda表达式
静态方法引用类名::staticMethod(args)->类名.staticMethod(args)
构建方法引用(类似于静态方法)类名::new(args)-> new 类名(args)
实例方法引用inst::instMethod(args)->inst.instMethod(args)
对象方法引用类名::instMethod(inst,args)->inst.instMethod(args)

注:

  1. 由于第三、四种方法引用存在对对象(inst)方法的直接调用(inst.instMethod),当对象inst为null时,可能出现NPE。

  2. 对于静态方法引用和对象方法引用无法直接通过名称判别,需要跳转到具体的函数实现,根据是否有static关键字进行区分。

  3. 为有效区分,不同于传统的类静态方法提供两种调用方式(类名,类对象),对类的静态方法只提供了类名::的引用方式。

  4. 对于第四种类型(由于实例(inst)实际作为lambda表达式中的参数,无法在每次调用前确定要具体调用的是哪个对象的方法,因此,需要使用类名::实例方法方法进行引用)

对象方法引用例子:

对于某个函数接口

@FunctionalInterface
public interface TestInf{
    public Result fun(FirstType firstType, SecondType secondType);
}

可将该方法的第一个参数的对象方法引用作为该函数接口的实现

例如

public FirstType{
    pulic Result testFun(SecondType secondType){
        return Result.ok("abc");
    }
}
// 可以理解为将上述函数式接口实现为
TestInf t = new TestInf(){
    @Override
    public Result fun(FirstType firstType, SecondType secondType){
        return firstType.testFun(secondType);
    }
}
// 等价的lambda写法为
TestInf t1 = (firstType,secondType)->firstType.testFun(secondType);
// 等价于对象引用的形式
TestInf t2 = FirstType::testFun;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值