Getting all instances of a class

Shawn Shroyer picture Shawn Shroyer · Apr 9, 2012 · Viewed 36.6k times · Source

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?

Answer

aleroot picture aleroot · Apr 9, 2012

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 
    }
  }