从字符串中按名称获取变量 [英] Get variable by name from a String

查看:34
本文介绍了从字符串中按名称获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

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();

然后,假设用户输入potato.我将如何检索名为 potato 的变量并使用它进行操作?像这样:

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

我查了一些东西,并没有找到多少;我确实找到了对反射 API"的引用,但这对于这个简单的任务来说似乎太复杂了.

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.

我需要将 String 保留在我正在做的变量中.(我不能使用 Map)

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

推荐答案

对于您在这里所做的事情,使用反射似乎不是一个好的设计.最好使用 Map 例如:

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);
}

或者使用 Guava:

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

或者使用枚举:

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);
    }
}

这篇关于从字符串中按名称获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆