开发者

Count Instances of Class

I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo. I want to be able to, in the same process, get a current count of all instan开发者_如何学JAVAce of Foo.

However I cannot modify Foo, so a static int with counting is out. Also I cannot just add all instances I make to some static list and count that. I want to be able to just say:

System.GC.numberOf< Foo >()

or something.

I was looking through the garbage collectors but I could not find any relevant methods.


If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?

public class subFoo extends foo
{
    protected static int count = 0;

    public subFoo() 
    {
        count++;
        super();
    }

    protected void finalize() throws Throwable
    {
        count--;
        super.finalize();
    } 

    public static int getInstanceCount()
    {
        return count;
    }
}

This example is Java and may have some syntax issues 'cause I'm a little rusty.

Of course, you'd have to be sure to redeclare all your foo as subFoo throughout the rest of your code.


Another somewhat exotic way to do it would be to use aspect-oriented techniques to instrument the constructor(s) of the class(es) in question. Take a look at AspectJ, for example.


Do you have control of how the Java VM is being run? If so, you can write a quick and dirty debugger agent... http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#writingAgents

See the events "VM Object Allocation" and "Object Free"


As already commented, there are similar questions in SO.
One hack you can use - a big one IMO - is to change the Object class: see this answer

Resume:

  • copy the source of Object
  • add counting to its constructor (finalize)
  • add method to read the count
  • prepend the directory with the compiled class to the boot classpath (-Xbootclasspath)


Quick and dirty: if you can't change the class, maybe you can just put a counter in another part of the project, incrementing it when you instantiate said class?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜