Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable by name from a String

Example code:

int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;

Now, say I want to have the user input a string:

String input = new Scanner(System.in).nextLine();

Then, say the user inputs potato. How would I retrieve the variable named potato and do stuff with it? Something like this:

System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4

I looked up some things and did not find much; I did find a reference to something called "the Reflection API," but that seems too complicated for this one simple task.

Is there a way to do this, and if so, what is it? If "Reflection" does indeed work and if it is the only way, then how would I use it to do this? The tutorial page for it has all sorts of internal stuff that I can't make any sense of.

EDIT: I need to keep the Strings in the variables for what I am doing. (I can't use a Map)

like image 901
tckmn Avatar asked Nov 08 '12 22:11

tckmn


1 Answers

Using reflection doesn't seem like a good design for what you're doing here. It would be better to use a Map<String, Integer> for example:

static final Map<String, Integer> VALUES_BY_NAME;
static {
    final Map<String, Integer> valuesByName = new HashMap<>();
    valuesByName.put("width", 5);
    valuesByName.put("potato", 2);
    VALUES_BY_NAME = Collections.unmodifiableMap(valuesByName);
}

Or with Guava:

static final ImmutableMap<String, Integer> VALUES_BY_NAME = ImmutableMap.of(
    "width", 5,
    "potato", 2
);

Or with an enum:

enum NameValuePair {

    WIDTH("width", 5),
    POTATO("potato", 2);

    private final String name;
    private final int value;

    private NameValuePair(final String name, final int value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    static NameValuePair getByName(final String name) {
        for (final NameValuePair nvp : values()) {
            if (nvp.getName().equals(name)) {
                return nvp;
            }
        }
        throw new IllegalArgumentException("Invalid name: " + name);
    }
}
like image 199
Paul Bellora Avatar answered Sep 24 '22 19:09

Paul Bellora