示例代码:
int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;
现在,假设我想让用户输入一个字符串:
String input = new Scanner(System.in).nextLine();
然后,假设用户输入 potato
。我将如何检索名为 potato
的变量并用它做些什么?像这样:
System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4
我查了一些东西,没找到多少;我确实找到了对称为“反射 API”的东西的引用,但对于这个简单的任务来说这似乎太复杂了。
有没有办法做到这一点,如果有,是什么?如果“反射”确实有效并且它是唯一的方法,那么我将如何使用它来做到这一点?它的教程页面包含各种我无法理解的内部内容。
编辑: 我需要将 String
保留在我正在做的事情的变量中。 (我不能使用 Map
)
最佳答案
对于您在这里所做的事情,使用反射似乎不是一个好的设计。最好使用 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);
}
或用Guava :
static final ImmutableMap<String, Integer> VALUES_BY_NAME = ImmutableMap.of(
"width", 5,
"potato", 2
);
或使用 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);
}
}
关于java - 从字符串中按名称获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298823/