Instead of changing your add
method, you should change the constructor for MyClass to this:
public MyClass()
{
Counter.add(this.getClass());
}
That way, you can use your HashMap<Class<?>, Integer>
(or whatever you're using to do the actual counting) like so:
if(map.containsKey(c))
{
map.put(c, map.get(c) + 1));
}
else
{
map.put(c, 1);
}
There is a potential problem with this counter idea: when an object becomes unreachable and gets collected, the counter won't decrease. So your counter will not be able to tell you how many objects you currently have, but how many you have created overall.