Create a sub class, override Constructor() and finalize(), inc a static counter when construct a new obj, desc the static counter when finalize the obj.

解决方案 »

  1.   

    to  billh2003(比尔) :
    这样是否太复杂了,一些应用服务器都可以判断内存中某个组件的实例数目和调用次数,他们不可能在用户提交的组件中再增加类似的代码吧?
    使用反射等Java机制是否可以实现呢?
      

  2.   

    declare a static field in constructor, when load constructor take the field +1
      

  3.   

    可以考虑像楼上所说
    static int count;
    public A(){
      count++;
    }
    public void getCount(){
    return count;
    }
      

  4.   

    给用户提供的组件A做一个wrapper类B,在
    如果不考虑垃圾收集机制的话,可以这样
    不能用new A生成A对象
    而是用B.createA方法生成A
    class B{
    static int n=0;
    static A createA(args....)
    {
         n++;
         return new A(args....);
    }如果要考虑垃圾收集的话,就必须在A中写一个finally方法了
    不过也可以利用一些特殊方法,如aspectj写而不用找到源代码了