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.

Share:
42,809

Related videos on Youtube

Shawn Shroyer
Author by

Shawn Shroyer

Updated on April 09, 2020

Comments

  • Shawn Shroyer
    Shawn Shroyer about 4 years

    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?

    • Mitch Wheat
      Mitch Wheat about 12 years
      since 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
    Vishy about 12 years
    A 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
    barneypitt over 7 years
    This is not a viable solution for my present problem ... I want to obtain instances of third-party classes.