获取类的所有实例 [英] Getting all instances of a class

查看:114
本文介绍了获取类的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

在java中,有没有可能的方法来获取某个类的所有实例?

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

推荐答案

在实例化您的类时,您可以使用Factory静态初始值设定器( Singleton模式),然后将每个生成的实例在工厂构造函数中添加到List ...

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

这样:

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

这篇关于获取类的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆