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.)
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With