为什么这两个方法参数不一样,还能方法引入?

为什么这两个方法参数不一样,还能方法引入?


回答:

一步一步简化,最后用方法引用表示只有一个方法调用的labmda表达式

u -> {return u.getAge();}
u -> return u.getAge()
Users::getAge

getAge() 其实可以视为两个方法:

  1. 无参的Integer getAge(),对应 Supplier<Integer>,方法引用是Users:getAge
  2. 有特殊参数的 Integer getAge(Users this),对应 Function<Users, Integer>,方法引用也是Users::getAge,符合comparing 的参数类型,于是可以用了


回答:

Java方法引用

类型方法引用Lambda表达式
静态方法引用Class::staticMethod(args) -> Class.staticMethod(args)
实例方法引用inst::instMethod(args) -> inst.instMethod(args)
对象方法引用Class::instMethod(inst,args) -> inst.instMethod(args)
构造方法引用Class::new(args) -> new Class(args)

这段代码中的“Users::getAge”适用于第三种情况“Class::instMethod”,方法的第一个参数就是对象实例。

也就是说

Users::getAge 对应的lambda表达式是 "(u Users) -> u.getAge()"


回答:

返回的参数一样

以上是 为什么这两个方法参数不一样,还能方法引入? 的全部内容, 来源链接: utcz.com/p/944799.html

回到顶部