Hi, how I can get all instances of a class on my application?
Thanks.
[Oh no, not static factories again ...]
You *could* use a factory instead of newing your instances:
private List instances = new ArrayList();
public static MyObject createMyObject() {
MyObject o = new MyObject();
instances.add(new java.lang.ref.WeakReference(o));
return o;
}
public static List getInstances() {
return instances;
}
private MyObject() {
// .. initialize ..
}
This won't hold your objects - when they go out of scope this allows
them to be collected. Two caveats of this: 1) if you're going to iterate
the list, you need to careful, as entries will silently removed -IIRC
the actual WeakReference will still be there, but it's get() will return
null. Also, 2) is that while your instances will be collected properly,
you've just swapped them for the references really. You'll need to
remove dead references from the list periodically (but at least you know
which are the dead ones).
There is a Map implementation with weak keys, which would automate the
removal for you (if you use your instance as the key), and allow you to
store something else with them if you needed to. You would need to look
into the equals semantics though (basically you want identity equality
if possible).
Also, notwithstanding all of that, you should *really* consider why you
want to do this, it is kinda indicative of bad design in most cases...