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


为什么这两个方法参数不一样,还能方法引入?
回答:
一步一步简化,最后用方法引用表示只有一个方法调用的labmda表达式
u -> {return u.getAge();}u -> return u.getAge()Users::getAgegetAge() 其实可以视为两个方法:
- 无参的
Integer getAge(),对应Supplier<Integer>,方法引用是Users:getAge - 有特殊参数的
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

