Accessing static field from Class variable

2019-09-16 18:54发布

I have the following situation (I know it doesn't sound real but I simplified it for better understanding):

  • A class A, with a public 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...

1条回答
甜甜的少女心
2楼-- · 2019-09-16 19:34

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:

int foo() {
    return A.f;
}

On success, that's what your current code will be returning anyway. Your code is equivalent to:

int foo(Class<A> classz) throws ... {
    A ignored = classz.newInstance();
    return A.f;
}

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 extra f fields within each subclass, then you've only got one field anyway - B.f and C.f will basically resolve to A.f anyway...

查看更多
登录 后发表回答