Java 使用对象状态调用方法的使用者
我有一节课Java 使用对象状态调用方法的使用者,java,lambda,Java,Lambda,我有一节课 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 v
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");
}
}
}
公共最终课程GGGGG{
私有最终字符串str;
公共GGGGG(最终字符串str){
this.str=str;
}
公共void showElement(最终字符串测试){
System.out.println(this.str+test);
}
公共静态void main(字符串[]args){
GGGGG hello=新GGGGG(“hello”);
final Test2 Test2=新的Test2(hello::showElement);
test2.test();
hello=null;
test2.test();
}
静态类Test2{
私人最终消费者;
测试2(最终消费者){
这个。消费者=消费者;
}
公开无效测试(){
这个。消费者。接受(“世界”);
}
}
}
我不明白的是,在GGGG类中,我有字符串str
(state)
我使用方法showElement
现在,这个消费者引用了GGGGG
实例。
消费者是否保留对原始对象的引用或创建新实例,如果它在垃圾收集时使用相同的引用?Java与So一起工作,test2
和hello
只是一个引用副本。您仍然保留要引用的信息
使用者是否保留对原始对象的引用
对
作为补充知识,描述了方法引用的运行时评估
方法参考表达式的计算时间比lambda表达式的计算时间更复杂(§15.27.4)。当方法引用表达式在::分隔符之前有表达式(而不是类型)时,将立即计算该子表达式。存储评估结果,直到调用相应功能接口类型的方法;此时,结果将用作调用的目标引用。这意味着,只有当程序遇到方法引用表达式时,才会对::分隔符前面的表达式求值,并且不会在函数接口类型的后续调用中重新求值
运行代码时会发生什么?Hello world打印两次