Access static final variable using reflection

前端 未结 1 1684
日久生厌
日久生厌 2020-12-11 01:22

I have a Java class with a static variable

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


        
相关标签:
1条回答
  • 2020-12-11 01:27

    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);
    }
    
    0 讨论(0)
提交回复
热议问题