I don't think reflection will help you. There is the JVMTI (and the older and now defunct JVMPI) which can be used to analyse the heap and determine the number of current instances of a class.
A coded alternative is to add a counter to the class you want to track instances of:
class Myclass {
static private final AtomicInteger count = new AtomicInteger();
{
count.getAndIncrement();
}
static public int instanceCount() {
return count.get();
}
// edit: account for serializable
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
counter.getAndIncrement();
ois.defaultReadObject();
}
}
This will track the number of instances ever created, and is thread-safe. To find out when instances are garbage collected, you can use a PhantomReference
and a ReferenceQueue
to track collected instances and decrement the counter.
class Myclass {
static private final AtomicInteger count = new AtomicInteger();
static private final ReferenceQueue<MyClass> queue = new ReferenceQueue<MyClass>();
{
count.getAndIncrement();
new PhantomReference<MyObject>(this, queue);
}
static public int instanceCount() {
return count.get();
}
static {
Thread t = new Thread() {
public void run() {
for (;;) {
queue.remove();
count.decrementAndGet();
}
}
};
t.setDaemon(true);
t.start();
}
}
EDIT:
If the class is serializeable, implement the readObject
method and increment the counter. I've added this to the first code example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…