2014-04-07 53 views
0

假设我创建了一个实现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填充,然后我可以一个接一个地调用清理方法。但是我没有看到如何在不使用反射的情况下解决上述问题。

回答

1

你不能用幻影引用做这样的事情,甚至没有反射会有帮助。在GC已经发生之后,您只能在ReferenceQueue中获得参考,因此没有更多的对象可以拨打close()

你可以做的一件事 - 一个好主意,事实上 - 是使用PhantomReference来抛出一个错误,说你应该直接调用close()而不是。例如,您可能会将对象对象引用到您的CustomPhantom,并调用CustomPhantom.setCleanedUp(true)方法。然后在您的CustomPhantom中,如果您处于ReferenceQueue并且未清理,则可以显示警告。

+0

感谢您的回答。我很困惑这个链接http://www.erpgreat.com/java/phantomreference-and-finalization.htm。那家伙说,我们可以使用反射从PhantomReference恢复对象 –

0

由于接受了答案,我只是添加更多信息。

当使用Java反射API来检查类PantomReferences,你不会得到现场所指将抛出NoSuchFieldException

相关问题