假设我创建了一个实现 Closable 的类 MyClass。因此,在 close() 方法中,我将释放一些非常重要的资源。好吧,因为它是非常重要的资源,所以我创建了某种安全网络(如《Effective Java》中所推荐的)。这是:
protected void finalize(){
if (/*user didn't call close() method by himself*/){
close();
}
}
一开始我很高兴,但后来我读到终结器并不是那么酷,而且有像 PhantomReference 这样很酷的工具。所以我决定更改代码以使用 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
}
}
因此,据我所知,获得对象引用的唯一方法是使用反射并从 Reference 类中的引用字段获取 if 。这是从清理方法调用 MyClass.close() 的唯一方法吗?
附注我没有在这里发布所有代码,但我测试了它并且一切正常。 ReferenceQueue 被 PhantomReferences 填充,然后我可以一一获取它们并调用 cleanup 方法。但我不知道如何在不使用反射的情况下解决上述问题。
最佳答案
你不能用幻像引用做这样的事情,甚至反射也无济于事。您只有在 GC 发生后才能获取 ReferenceQueue
中的引用,因此不再有对象可以调用 close()
。
您可以做的一件事 - 事实上,这是一个好主意 - 是使用 PhantomReference
抛出一个错误,说明您应该调用 close()
直接并没有。例如,您可能让引用对象引用您的 CustomPhantom
,并调用 CustomPhantom.setCleanedUp(true)
方法。然后,在 CustomPhantom
中,如果您位于 ReferenceQueue
中且未清理,则可以显示警告。
关于java - 我是否会在使用 PhantomReferences 完成时避免使用反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22922170/