从String获取名称变量

Doo*_*nob 14 java string reflection variables

示例代码:

int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;
Run Code Online (Sandbox Code Playgroud)

现在,假设我想让用户输入一个字符串:

String input = new Scanner(System.in).nextLine();
Run Code Online (Sandbox Code Playgroud)

然后,说用户输入potato.我如何检索名为的变量potato并用它做一些东西?像这样的东西:

System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4
Run Code Online (Sandbox Code Playgroud)

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

有没有办法做到这一点,如果是这样,它是什么?如果"反射"确实有效并且如果它是唯一的方法,那么我将如何使用它来做到这一点?它的教程页面有各种内部的东西,我无法理解.

编辑:我需要将Strings 保留在我正在做的变量中.(我不能用Map)

Pau*_*ora 16

使用反射对于你在这里所做的事情来说似乎不是一个好的设计.最好使用Map<String, Integer>例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

或者与番石榴:

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

或者使用枚举:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我需要将变量中的`String`s保留在我正在做的事情中. (2认同)