java 使用反射访问静态最终变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7992448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:35:43  来源:igfitidea点击:

Access static final variable using reflection

javareflectionstatic

提问by M S

I have a Java class with a static variable

我有一个带有静态变量的 Java 类

package com.mytest
public class MyClass{
    public static final TextClass TEXT_CLASS = new TextClass();
}

How can I access the object TEXT_CLASSusing reflection?

如何TEXT_CLASS使用反射访问对象?

(I have the string "com.mytest.MyClass.TEXT_CLASS". I need to access the object.)

(我有字符串"com.mytest.MyClass.TEXT_CLASS"。我需要访问该对象。)

回答by socha23

Accessing static fields is done exactly the same way as normal fields, only you don't need to pass any argument to Field.get()method (you can pass a null).

访问静态字段的方式与普通字段完全相同,只是您不需要将任何参数传递给Field.get()方法(您可以传递一个空值)。

Try this:

试试这个:

Object getFieldValue(String path) throws Exception {
    int lastDot = path.lastIndexOf(".");
    String className = path.substring(0, lastDot);
    String fieldName = path.substring(lastDot + 1);
    Class myClass = Class.forName(className);
    Field myField = myClass.getDeclaredField(fieldName);
    return myField.get(null);
}