Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...