简体   繁体   English

我可以访问“类”Object 的 static 变量吗?

[英]Can I access the static variables of the 'Class' Object?

Having this method:有这个方法:

readAllTypes(Class clazz) {...}

Can I access the static variables of the class?我可以访问 class 的 static 变量吗?

Yes.是的。 Just use Class.getDeclaredFields() (or Class.getDeclaredField(String) ) as normal, and to get the values, use the Field.getXyz() methods, passing in null for the obj parameter.只需正常使用Class.getDeclaredFields() (或Class.getDeclaredField(String) ),并获取值,使用obj Field.getXyz()方法,传入null参数。D

Sample code:示例代码:

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

You can find the field using clazz.getDeclaredFields() , which returns a Field[] , or by directly getting the field by name, with clazz.getDeclaredField("myFieldName") .您可以使用返回Field[]clazz.getDeclaredFields()找到该字段,或者使用clazz.getDeclaredField("myFieldName")直接按名称获取该字段。 This may throw a NoSuchFieldException .这可能会引发NoSuchFieldException

Once you've done that, you can get the value of the field with field.get(null) if the field represents an object, or with field.getInt(null) , field.getDouble(null) , etc. if it's a primitive.完成此操作后,如果字段表示 object,则可以使用 field.get(null field.get(null)获取字段的值,或者如果是field.getInt(null)field.getDouble(null)等原始。 To check the type of the field, use the getType or getGenericType .要检查字段的类型,请使用getTypegetGenericType These may throw an IllegalAccessException if they're not public, in which case you can use field.setAccessible(true) first.如果它们不公开,它们可能会抛出IllegalAccessException ,在这种情况下,您可以先使用field.setAccessible(true) You can also set the fields in the same way if you just replace "get" with "set".如果您只是将“get”替换为“set”,您也可以以相同的方式设置字段。

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

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