简体   繁体   中英

Access static final variable using reflection

I have a Java class with a static variable

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

How can I access the object TEXT_CLASS using reflection?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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