3

What I want to do is access a variable stored in one class with a string. For example I have

public class Values {
    public static boolean enabled;
}

And then in a different part of the project I have the object and a string with the fields name. How do I get and set the value of the field?

1
  • 1
    I'm not sure what's worse: the blatant global state or the inappropriate use of reflection. Commented Jun 10, 2012 at 0:22

3 Answers 3

9

If you have the name as a string, you should use reflection:

import java.lang.reflect.Field;


public class Values {

    public static boolean enabled = false;

    public static void main(String[] args) throws Exception {           
        Values v = new Values();

        Field field = v.getClass().getField("enabled");

        field.set( v, true );

        System.out.println( field.get(v) );         
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Suggestion. OP asked also how to get value of field, so maybe use in code something like System.out.println(field.get(v)); instead of System.out.println( Values.enabled );. Anyway nice example. +1
Nice catch, didn't notice that :)
1
Values.enabled = true;

or

Values.enabled = false;

Alternatively, you can create a static getter and setter for the Values class and call those static methods instead.

2 Comments

The only problem with this is that all I have is a string with the name of the field and the Values object. Could I use reflection to get and set the boolean?
With a string; I think the OP is asking about reflection.
1

@Maricio Linhares's answer is very good; however, note that reflection is pretty slow. If you are doing this a lot you might have performance problems. An alternative might be to use a map. The code would follow as

public class Values {
    public static Map<string,bool> variableMap;

    public static void main(String[] args) throws Exception {           
        // adding a 'variable'
        variableMap = new YourFavoriteMapImplementation();
        variableMap.put("enabled",true);

        // accessing the 'variables' value
        bool val = variableMap.get("enabled");
        System.out.println(val);         
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.