Getting all instances of a class
42,809
Solution 1
You can use a Factory static initializer when you instantiate your class (Singleton pattern) and then add each generated instance in the factory constructor to a List ...
Something like this :
class MyObject {
private static 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() {
// Not allowed
}
}
Solution 2
Not in general. If you're using the debugger API it may be possible (I haven't checked) but you shouldn't use that other than for debugging.
If your design requires this, it's probably worth rethinking that design.
Related videos on Youtube
Author by
Shawn Shroyer
Updated on April 09, 2020Comments
-
Shawn Shroyer about 4 years
Possible Duplicate:
Is there a simple way of obtaining all object instances of a specific class in JavaIn java, is there any possible way to get all the instances of a certain class?
-
Mitch Wheat about 12 yearssince you would be instantiating them, simply keep a (weak? does java have weak references?) reference to each instance. But I would suspect any design that required this...
-
-
Vishy about 12 yearsA weak hash set might be a nicer collection as it cleans up such references transparently.
Set<MyObject> instances = Collections.newSetFromMap(new WeakHashMap<MyObject, Boolean>());
-
barneypitt over 7 yearsThis is not a viable solution for my present problem ... I want to obtain instances of third-party classes.