Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get static variable from class stored in Class variable

Tags:

java

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.

like image 763
lawls Avatar asked Apr 23 '26 17:04

lawls


2 Answers

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);
    }
}
like image 73
Kevin Bowersox Avatar answered Apr 26 '26 06:04

Kevin Bowersox


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.

like image 22
Sebastian Redl Avatar answered Apr 26 '26 06:04

Sebastian Redl