gpt4 book ai didi

java - 使用对象状态调用方法的消费者

转载 作者:行者123 更新时间:2023-11-30 02:04:56 25 4
gpt4 key购买 nike

我有课

public final class GGGGG {

private final String str;

public GGGGG(final String str) {
this.str = str;
}

public void showElement(final String test){
System.out.println(this.str+test);
}

public static void main(String[] args) {
GGGGG hello = new GGGGG("hello");
final Test2 test2 = new Test2(hello::showElement);
test2.test();
hello = null;
test2.test();

}

static class Test2{
private final Consumer<String> consumer;

Test2(final Consumer<String> consumer) {
this.consumer = consumer;
}

public void test(){
this.consumer.accept(" world");
}
}
}

我不明白,在GGGG课上我有String str (状态)

我创建了一个消费者,其方法引用了方法 showElement现在这位消费者引用了GGGGG实例。消费者是否保留对原始对象的引用或创建一个新实例,如果它在被垃圾收集时具有相同的引用?

最佳答案

Java 可与 pass-by-value. 配合使用因此,test2hello 只是引用副本。您仍然保留引用位置的信息。

Does consumer keep a reference to the original object?

是的。

作为附加知识,JLS, Section 15.13.3描述方法引用的运行时评估。

The timing of method reference expression evaluation is more complex than that of lambda expressions (§15.27.4). When a method reference expression has an expression (rather than a type) preceding the :: separator, that subexpression is evaluated immediately. The result of evaluation is stored until the method of the corresponding functional interface type is invoked; at that point, the result is used as the target reference for the invocation. This means the expression preceding the :: separator is evaluated only when the program encounters the method reference expression, and is not re-evaluated on subsequent invocations on the functional interface type.

关于java - 使用对象状态调用方法的消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649370/

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