27

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?

Community
  • 1
  • 1
Shawn Shroyer
  • 901
  • 1
  • 8
  • 18
  • 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... – Mitch Wheat Apr 09 '12 at 09:06

2 Answers2

29

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 
    }
  }
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • 4
    A weak hash set might be a nicer collection as it cleans up such references transparently. `Set instances = Collections.newSetFromMap(new WeakHashMap());` – Peter Lawrey Apr 09 '12 at 09:38
  • 3
    This is not a viable solution for my present problem ... I want to obtain instances of third-party classes. – barneypitt Sep 05 '16 at 16:01
9

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194