我可以访问“类”对象的静态变量吗?

SG *_*dge 7 java class

有了这个方法:

readAllTypes(Class clazz) {...}
Run Code Online (Sandbox Code Playgroud)

我可以访问类的静态变量吗?

Jon*_*eet 10

是的。仅在使用Class.getDeclaredFields()(或Class.getDeclaredField(String))为正常,得到的值,使用Field.getXyz()方法,在传递nullobj参数。

示例代码:

import java.lang.reflect.Field;

class Foo {
    public static int bar;
}

class Test {
    public static void main(String[] args)
        throws IllegalAccessException, NoSuchFieldException {

        Field field = Foo.class.getDeclaredField("bar");
        System.out.println(field.getInt(null)); // 0
        Foo.bar = 10;
        System.out.println(field.getInt(null)); // 10
    }
}
Run Code Online (Sandbox Code Playgroud)