Given a class (ex: foo.bar.MyClass), how can I get a count of the number of instances of that class existing within the JVM?
Thanks
EDIT: I’m looking for the code that will retrieve this count.
EDIT: More specifically, an implementation of the method Integer getInstanceCount(Class c)
There are three or even four possible answers depending on the exact context. Here they are:
If you can change the source code of the class, then you can add a static counter (see @The Feast’s answer)
If you’re having memory problems then you should use a memory profiler (see @winSharp93) such as: http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html,
If you don’t have access to the source code you can register an instrumentation agent with the JVM which will inject that static field into the classes that interest you (not trivial, but possible). A tutorial on instrumentation is available here: http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html
If you were looking for some Java API that exposes this information, then – sadly – the answer is that no such facility is supported.