简体   繁体   English

从类<A>变量</a>访问静态字段

[英]Accessing static field from Class<A> variable

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; A class A ,带有public static int f; declared 声明
  • Other classes B, C, D, ... that extend A 其他类B, C, D, ...延伸A
  • A method foo (somewhere else, doesn't matter) with the following signature: int foo(Class< A> classz); 方法foo (在其他地方无关紧要)具有以下签名: 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 ; 现在我希望这个方法实现返回值,如果静态字段f ,来自classz表示的类; subclasses of A may have different values. A子类可能具有不同的值。 I don't want to use reflection (and neither the new jdk7 invoke.* features). 我不想使用反射(也没有新的jdk7调用。*功能)。 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... PS:不知道如何在没有空格的情况下输入Class< ?>

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. 如果你在每个子类中声明额外的f字段,你不得不使用反射来获取它们,但我建议你重新设计。 If you're not declaring extra f fields within each subclass, then you've only got one field anyway - Bf and Cf will basically resolve to Af anyway... 如果你没有在每个子类中声明额外的f字段,那么你只有一个字段BfCf基本上会解析为Af ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM