gpt4 book ai didi

Java 8 : Difference between method reference Bound Receiver and UnBound Receiver

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:39 27 4
gpt4 key购买 nike

我正在尝试在我的代码中使用 Java 8 方法引用。有四种类型的方法引用可用。

  1. 静态方法引用。
  2. 实例方法(绑定(bind)接收器)。
  3. 实例方法(UnBound 接收器)。
  4. 构造函数引用。

使用静态方法引用构造函数引用我没问题,但是Instance Method (Bound receiver)Instance Method ( UnBound receiver) 真的让我很困惑。在 Bound 接收器中,我们使用对象引用变量来调用如下方法:

objectRef::Instance Method

UnBound 接收器中,我们使用类名来调用如下方法:

ClassName::Instance Method.

我有以下问题:

  1. 实例方法对不同类型方法引用的需求是什么?
  2. BoundUnbound 接收器方法引用有什么区别?
  3. 我们应该在什么地方使用Bound 接收器,在什么地方使用Unbound 接收器?

我还从Java 8 language features books 找到了BoundUnbound 接收器的解释。 , 但仍然与实际概念混淆。

最佳答案

String::length 等 unBound 接收者的想法是你指的是一个将作为 lambda 参数之一提供的对象的方法。例如,lambda 表达式 (String s) -> s.toUpperCase() 可以重写为 String::toUpperCase

但是有界指的是你在一个方法中调用一个方法的情况lambda 到一个已经存在的外部对象。例如,lambda 表达式 () ->expensiveTransaction.getValue() 可以重写为 expensiveTransaction::getValue

方法引用的三种不同方式的情况

(args) -> ClassName.staticMethod(args)可以是 ClassName::staticMethod//这是静态的(你也可以认为是未绑定(bind)的)

(arg0, rest) -> arg0.instanceMethod(rest)可以是 ClassName::instanceMethod(arg0ClassName 类型)//这是未绑定(bind)的

(args) -> expr.instanceMethod(args)可以是 expr::instanceMethod//This is Bound

Java 8 in Action 一书中检索到的答案

关于Java 8 : Difference between method reference Bound Receiver and UnBound Receiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35914775/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com