简体   繁体   English

我们可以使用反射来获取类的静态成员而无需在对象实例上调用该方法吗?

[英]Can we use reflection to get a static member of a class without invoking that method on an object instance?

Can we use reflection to get a static member of a class without invoking that method on an object instance? 我们可以使用反射来获取类的静态成员而无需在对象实例上调用该方法吗?

In other words: 换一种说法:

 public class MuchoStatic {

    private static staticMember;

    getStaticMember(){

    return this.staticMember;

    }
    } //end class

then there's more code: 然后有更多代码:

Method m = null;

try{

  m = MuchoStatic.class.getMethod("getStaticMember",null);

} catch (Exception e) {

}

Object o = null;
try{

 o = m.invoke(MuchoStatic.class,null);

} catch (Exception e) {

}

I am getting an illegal argument exception, I assume it's because I am passing a Class object into the invoke method. 我收到一个非法的参数异常,我想这是因为我正在将Class对象传递给invoke方法。 It turns out the Object o is actually instatiated, but the exception is still thrown. 事实证明,对象o实际上是无效的,但是仍然引发异常。

Shouldn't we be able to do this? 我们不应该能够做到这一点吗?

Can we use reflection to get a static member of a class without invoking that method on an object instance? 我们可以使用反射来获取类的静态成员而无需在对象实例上调用该方法吗?

Of course, as it is static. 当然,因为它是静态的。

Object o = null;
try {
    Method m = MuchoStatic.class.getMethod("getStaticMember");
    m.setAccessible(true);
    o = m.invoke(null);

} catch (Exception e) {
    // don't ignore the exception as it may be trying to tell you something
    throw new AssertionError(e);
}

You don't need an instance to invoke the static method and since it doesn't take any arguments, simply 不需要实例来调用静态方法,并且由于它不需要任何参数,因此只需

o = m.invoke(null);

If your classes are not in the same package, you will have problems however, because the method is declared as package private. 如果您的类不在同一个包中,则将有问题,因为该方法被声明为私有包。 You might need to call 您可能需要致电

m.setAccessible(true);

before invoke() . invoke()之前。

If we use 如果我们使用

setAccessible(true);

with the field, it is not even needed to have the method in the equation 在现场,甚至不需要方程中的方法

Field f = MuchoStatic.class.getField("staticMember");
Object theStatic = f.get(null);

Of course, this is not recommended... Tinkering with private is not a nice thing. 当然, 建议这样做。与私人进行修补不是一件好事。 Don't tinker others privates ! 不要修补其他私人

Ideone fiddle 伊迪奥小提琴

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

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