【发布时间】:2020-04-26 06:07:28
【问题描述】:
请在下面查看我的代码。我有一个带有方法的功能接口 IFace。我正在使用来自 Test 的类实例的方法引用创建一个实现。谁能告诉我即使引用无效,接口仍然如何引用实例方法?还是引用改变了...?
public class Test {
private int intVar;
public Test() {
intVar = 123;
}
public Test(int intVar) {
this.intVar = intVar;
}
public void myInstanceMethod() {
System.out.println("Hello from instance: " + intVar);
}
public static void main(String[] args) {
Test t = new Test();
IFace i = t::myInstanceMethod;
i.method(); // Hello from instance: 123
t = null; // Nullifying the reference
i.method(); // Hello from instance: 123
// Why still executing the method if reference is nullified?????
t = new Test(456);
i.method(); // Hello from instance: 123
// Why not Hello from instance: 456 ??????
}
static interface IFace {
void method();
}
}
【问题讨论】:
-
你可以检查
t==i是否(指向同一个地址空间),如果不是那么一切都好,如果是那么它是一个问题,快乐学习。另请注意:对象地址空间与引用变量的地址空间不同。 -
t = null;不影响 i。 -
t 和 i 的字符串表示 com.test.javaadvanced.Test@1218025c com.test.javaadvanced.Test$$Lambda$1/531885035@816f27d
-
t = null;或t = new Test(456);永远不会在您的代码中再次使用。您使用已分配捕获值的i。
标签: java java-8 method-reference