I am currently experimenting with reflection and I recently came across a question. I have this method, which calculates the size (unit: bytes) of a class consisting only of primitive typed fields (excluding booleans) as follows:
import java.lang.reflect.Field;
public class Foo {
// [...]
// Works only for classes with primitive typed fields (excluding booleans)
public int getSize() {
int size = 0;
for (Field f : getClass().getDeclaredFields()) {
try {
f.setAccessible(true);
Object obj = f.get(this);
Field objField = obj.getClass().getDeclaredField("SIZE");
int fieldSize = (int) objField.get(obj);
size += fieldSize / Byte.SIZE;
} catch (Exception e) {
e.printStackTrace();
}
}
return size;
}
}
As you can see the method cannot be static, since it contains non-static stuff like getClass() and this. However, for every instance of this class the return value of getSize() will be the same, which also holds for every class which extends Foo (of course, with a different value). Hence, conceptually getSize() has a static nature.
Is there a way to make this method static? I thought of using a static class reference like Foo.class to get around getClass() but this would basically destroy the semantics of getSize() for classes which extend Foo. I currently do not think it is possible since static methods are not inherited, but I am not 100% sure if there might be a little tweak to handle this issue.
So what’s wrong with doing something like