从类< A>访问静态字段变量 [英] Accessing static field from Class<A> variable

查看:94
本文介绍了从类< A>访问静态字段变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况(我知道它不是真的,但我简化了它为了更好地理解):



(其他地方,无关紧要)

现在我想要这个方法实现返回值,如果静态字段 f ,从 classz ; A 的子类可能有不同的值。我不想使用反射(和新的jdk7 invoke。*功能)。现在,我有这个解决方案工作,但不好,因为它instanciates一个对象(这不应该是必要的),并通过访问一个静态字段从一个实例生成警告:

  int foo(Class< A> classz)throws [do not matter] {
return classz.newInstance()。
}

有任何建议吗?
提前感谢?



PS:不知道如何输入 Class< ?> 没有空格...

解决方案

do或为什么你传递一个类 - 它看起来像你应该只需要:

  int foo(){ 
return Af;
}

成功后,这就是你当前的代码将返回。您的代码等效于:

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

这听起来像是你多态与静态字段 - 这根本不工作。静态成员不是多态的,也不是字段。如果您在每个子类别中声明额外的 f 字段,您将必须使用反射来获取它们,但我建议您重新设计。如果您在每个子类中声明额外的 f 字段,则您只有一个字段 - Bf Cf 将基本解析为 Af $ b

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

解决方案

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

这篇关于从类&lt; A&gt;访问静态字段变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆