I have the following situation (I know it doesn't sound real but I simplified it for better understanding):
- A
class A
, with apublic static int f;
declared - Other classes
B, C, D, ...
that extend A - A method
foo
(somewhere else, doesn't matter) with the following signature:int foo(Class< A> classz);
Now I want this method implementation to return the value if the static field f
, from the class represented by classz
; subclasses of A
may have different values. I don't want to use reflection (and neither the new jdk7 invoke.* features). For now, I have this solution that works, but isn't good, since it instanciates an object (which should not be necessary) and it generate a warning by accessing a static field from an instance:
int foo(Class< A> classz) throws [don't matter] {
return classz.newInstance().f;
}
Any suggestions? Thanks in advance?
PS: Don't know how to type Class< ?>
without the space...
It's not really clear what you're trying to do or why you're passing in a class at all - it looks like you should just need:
On success, that's what your current code will be returning anyway. Your code is equivalent to:
It sounds like you're trying to use polymorphism with static fields - that's simply not going to work. Static members aren't polymorphic, and neither are fields. If you're declaring extra
f
fields within each subclass, you would have to use reflection to get at them, but I advise you to redesign anyway. If you're not declaring extraf
fields within each subclass, then you've only got one field anyway -B.f
andC.f
will basically resolve toA.f
anyway...