QVSJ
QVSJ

Reputation: 1185

To fetch the value of a variable using the name of the variable, passed over as a variable value

Using Java,I have to fetch multiple sets of values from an XML file to use in my code. It just so happens that, one of the values I retrieve is the name of a static variable(the value of which is defined in a class file.) I need to find a way to fetch the value of the static variable using the name of the variable I get from the XML file.

Help?

Upvotes: 1

Views: 163

Answers (3)

RP-
RP-

Reputation: 5837

Use reflection API, You can get static variable names of a class as follows.

Field[] fields = YourClass.class.getDeclaredFields();

Then you can iterate them and compare with your xml name values.

Upvotes: 1

Ahmad Y. Saleh
Ahmad Y. Saleh

Reputation: 3349

Using reflection, as follows:

Field f1 = <ClassHavingTheStaticField>.class.getDeclaredField("<staticFieldName>");
Object o = f1.get(null);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074028

You can use Class.forName to load the class (if necessary; if you have a direct reference to it just use ClassName.class), then Class#getField and Field#get for that:

import java.lang.reflect.*;

public class GetTheStatic {
    public static final void main(String[] args) {
        String className;
        String fieldName;
        Class cls;
        Field fld;
        String value;

        if (args.length != 2) {
            System.out.println("Need [classname] [fieldName]");
            System.exit(-1);
        }

        try {
            className = args[0];
            fieldName = args[1];

            cls = Class.forName(className);
            fld = cls.getField(fieldName);
            value = (String)fld.get(cls);
            System.out.println("Field value is " + value);
            System.exit(0);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            System.exit(-1);
        }
    }
}

Assuming I have this other class:

public class TheStatic {
    public static String foo = "bar";
}

Then this:

java GetTheStatic TheStatic foo

outputs

Field value is bar

Upvotes: 1

Related Questions