You can't do something like this with phantom references, and not even reflection will help. You only get the reference in the ReferenceQueue
after GC has already occurred, so there's no more object to call close()
on.
One thing you can do -- a good idea, in point of fact -- is to use the PhantomReference
to throw an error saying you should have called close()
directly and didn't. For example, you might have the referent object have a reference to your CustomPhantom
, and call a CustomPhantom.setCleanedUp(true)
method. Then in your CustomPhantom
, if you're in a ReferenceQueue
and it's not cleaned up, you can display a warning.