Accessing static field from Class<A> variable

孤街醉人 提交于 2020-01-17 05:09:31

问题


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:


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...



来源:https://stackoverflow.com/questions/8019507/accessing-static-field-from-classa-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!