Hi, how I can get all instances of a class on my application?
Thanks.
Roland - 19 May 2005 12:17 GMT
> Hi, how I can get all instances of a class on my application?
>
> Thanks.
The Java API doesn't have a way to track instances of a class. If
required, however, you could build a mechanism into your application.
But why do you want to know it in the first place?

Signature
Regards,
Roland de Ruiter
___ ___
/__/ w_/ /__/
/ \ /_/ / \
Ross Bamford - 20 May 2005 01:28 GMT
> 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...

Signature
[Ross A. Bamford] [ross AT the.website.domain]
Roscopeco Open Tech ++ Open Source + Java + Apache + CMF
http://www.roscopec0.f9.co.uk/ + info@the.website.domain
Joona I Palaste - 20 May 2005 16:19 GMT
JML <no-spam@no-spam.com> scribbled the following:
> Hi, how I can get all instances of a class on my application?
> Thanks.
There is no general way. For classes you design yourself, you could add
code to the constructor that updates a static data structure. This gives
you all instances ever created. At the same time it prevents those
objects from ever being swept up by the GC, which might cause problems
with memory. To solve that, you would have to add an explicit
"relinquish" method that would remove the instance from the static data
structure, and remember to call it when you're done with the object.

Signature
/-- Joona Palaste (palaste@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"I am looking for myself. Have you seen me somewhere?"
- Anon