Is there any way this can be done:
Class cls = MyClass.class;
int variable = cls.staticVariable;
Class MyClass {
public static int staticVariable = 5;
}
Class cls will always contain a class that has the variable staticVariable, but it won't always be the same class. Hope you understand.
Here is a short working example demonstrating the concept via reflection.
public class ReflectionStatic {
public static int staticVariable = 5;
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
Class<ReflectionStatic> clazz = ReflectionStatic.class;
int value = clazz.getField("staticVariable").getInt(null);
System.out.println(value);
}
}
Yes, but only via the reflection API.
Field f = cls.getField("staticVariable");
int variable = f.getInt(null);
There will be a lot of exceptions for you to catch here.
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