假设我创建了一个实现Closable的类MyClass。所以在close()方法中,我将释放一些非常重要的资源。那么因为它是非常重要的资源,我创建了一些安全网络(正如Effective Java所推荐的那样)。那就是:我是否会在使用PantomReferences进行最终化时避免使用Reflection?
protected void finalize(){
if (/*user didn't call close() method by himself*/){
close();
}
}
首先,我很高兴,但后来我读了终结是不是很爽,并且有像幻影这样一个很酷的工具。所以我决定改变我的代码来使用PhantomReference而不是finalize()方法。我创建了CustomPantom扩展了PhantomRefernce。那就是:
public class CustomPhantom extends PhantomReference {
//Object cobj;
public CustomPhantom(Object referent, ReferenceQueue q) {
super(referent, q);
//this.cobj = referent; can't save the refference to my object in a class field,
// because it will become strongly rechable
//and PhantomReference won't be put to the reference queue
}
public void cleanup(){
//here I want to call close method from my object,
//but I don't have a reference to my object
}
}
所以,我看到我能得到我的对象的引用,唯一的办法就是使用反射,并从指涉领域这是在参考类得到,如果。这是从清理方法调用MyClass.close()的唯一方法吗?
P.S.我没有在这里发布所有的代码,但我测试了它,一切正常。 ReferenceQueue由PhantomReferences填充,然后我可以一个接一个地调用清理方法。但是我没有看到如何在不使用反射的情况下解决上述问题。
感谢您的回答。我很困惑这个链接http://www.erpgreat.com/java/phantomreference-and-finalization.htm。那家伙说,我们可以使用反射从PhantomReference恢复对象 –