get all instances of a class

R

Roland

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?
--
Regards,

Roland de Ruiter
___ ___
/__/ w_/ /__/
/ \ /_/ / \
 
R

Ross Bamford

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...
 
J

Joona I Palaste

JML said:
Hi, how I can get all instances of a class on my application?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top