Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 394
M S Avatar asked Nov 03 '11 09:11

M S


People also ask

Can we access final variable in static method?

We can initialize a final static variable at the time of declaration. Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.

How do I change the value of the final static variable in Java?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.

How do you use static access?

Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference. We can only declare static variables at the class level. We can access static fields without object initialization.

Can we change static variable in Java?

Static Methods in JavaThe static methods of a particular class can only access the static variables and can change them. A static method can only call other static methods. Static methods can't refer to non-static variables or methods.


1 Answers

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);
}
like image 191
socha23 Avatar answered Oct 19 '22 03:10

socha23