is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?
Imagine I\'ve got access to the root class (e.g. object), an
In Java you can implement the counting function to the common super class of your hirachy.
This base class contains a Map - associating the classes to the number of instances. If a instance of base or one of its sub class is created, then the constructor ins invoked. The constructor increase the number of instances of the concreate class.
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
public class Base {
/** Threadsave counter */
private static final ConcurrentMap, AtomicInteger>
instancesByClass
= new ConcurrentHashMap, AtomicInteger>(
10);
/** The only one constructor of base */
public Base() {
Class extends Base> concreateClass = this.getClass();
AtomicInteger oldValue = instancesByClass.putIfAbsent(concreateClass,
new AtomicInteger(1));
if (oldValue != null) {
oldValue.incrementAndGet();
}
}
/* DEMO starts here */
public static class SubA extends Base{
}
public static class SubB extends Base{
}
public static class SubSubA extends SubA{
}
public static void main(String[] args) {
printNumbers();
new SubA();
new SubA();
new SubB();
new SubSubA();
printNumbers();
}
private static void printNumbers() {
// not thread save!
for (Entry, AtomicInteger> item : instancesByClass
.entrySet()) {
System.out.println(item.getKey().getName() + " : "
+ item.getValue());
}
}
}