Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all instances of a class [duplicate]

Tags:

Possible Duplicate:
Is there a simple way of obtaining all object instances of a specific class in Java

In java, is there any possible way to get all the instances of a certain class?

like image 279
Shawn Shroyer Avatar asked Apr 09 '12 09:04

Shawn Shroyer


Video Answer


2 Answers

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      }   } 
like image 191
aleroot Avatar answered Oct 21 '22 00:10

aleroot


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.

like image 36
Jon Skeet Avatar answered Oct 21 '22 02:10

Jon Skeet