Reputation: 1363
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?
Upvotes: 3
Views: 698
Reputation: 1279
@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);
}
}
Upvotes: 1
Reputation: 40333
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) );
}
}
Upvotes: 9
Reputation: 122376
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.
Upvotes: 1