Why is there no StrongReference object?

leenster

New Member
I'm implementing some behavior which could benefit from using weak references some of the time. I'd like the user of the class to be able to indicate at construction time whether this is the case or not. Since \[code\]WeakReference\[/code\] extends \[code\]Reference\[/code\] at first glance it would seem I could do something like (this is a mockup, not what I'm actually trying to do):\[code\]public class Container<T> { private boolean useWeakRef; private Reference<T> ref; public Containaer(boolean isWeak) { useWeakRef = isWeak; } public void store(T val) { if(useWeakRef) { ref = new WeakReference<>(val); } else { ref = new StrongReference<>(val); } } // May return null public T get() { return ref.get(); }}\[/code\]However there is no \[code\]StrongReference\[/code\] class, and according to the Reference javadocs:\[quote\] Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.\[/quote\]So I can't create my own subclass of Reference that holds a strong (i.e. normal) reference to the object. This seems to mean it's not possible to make a class which hides whether it uses Weak (or Soft) references from the caller.I don't really understand why this class doesn't exist, a \[code\]StrongReference\[/code\] object should simply always return the object from get() unless clear() has been called. Why is this missing? It would make building generic reference-holder objects much simpler.
 
Back
Top