Getting all instances of a class [duplicate]

大憨熊 提交于 2019-11-28 09:42:54

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!