请参阅下面的代码。我有一个带有方法的功能接口IFace。我正在使用Test的类实例中的Method引用创建一个实现。有人能告诉我,即使引用无效,接口如何仍然引用实例方法吗?或者引用被更改。。。?
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();
}
}
从某种意义上说,这个问题类似于在以下程序中询问为什么打印b
不输出null
:
String a = "abc";
String b = a;
a = null;
System.out.println(b);
当IFace i = t::myInstanceMethod;
完成运行时,i
已经捕获到对t
此时指向的对象的引用。该引用独立于变量t
。把它看作i
,方法引用有自己的变量指向同一个对象。
当您使引用无效时,内存不会被释放。当所有引用都消失时,它就被释放了。通过传递方法引用,您创建了对对象本身的新引用,因此此时引用计数为2,即i在下保持对t的引用