正如主题所说:未引用的对象可以再次引用吗?
我在http://www.javatpoint.com/corejava-interview-questions-4遇到了这个问题Q120。我尝试用谷歌搜索这个但没有找到任何链接。我们实际上如何做到这一点?
最佳答案
下面的示例不是“野外”示例,但它演示了如何通过 finalize
方法“复活”未引用的对象。这种情况只可能发生一次。如果第一个实例的对象第二次变为未引用,则不会再次调用 finalize()
方法。
public class Resurrect {
static Resurrect resurrect = null;
public static void main(String[] args) {
Resurrect localInstance = new Resurrect();
System.out.println("first instance: " + localInstance.hashCode());
// after this code there is no more reference to the first instance
localInstance = new Resurrect();
System.out.println("second instance: " + localInstance.hashCode());
// will (in this simple example) request the execution of the finalize() method of the first instance
System.gc();
}
@Override
public void finalize() {
resurrect = this;
System.out.println("resurrected: " + resurrect.hashCode());
}
}
关于java - 未引用的对象可以再次引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743096/