示例代码:
int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;
现在,假设我想让用户输入一个字符串:
String input = new Scanner(System.in).nextLine();
然后,说用户输入马铃薯.我如何检索名为potato的变量并用它做一些事情?像这样的东西:
System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4
我查了一些东西并没有找到太多东西;我确实找到了一个名为“Reflection API”的引用,但这对于这个简单的任务来说似乎太复杂了.
有没有办法做到这一点,如果是这样,它是什么?如果“反射”确实有效并且如果它是唯一的方法,那么我将如何使用它来做到这一点?它的教程页面有各种内部的东西,我无法理解.
编辑:我需要将字符串保存在我正在做的变量中. (我不能使用地图)
解决方法:
对于你在这里所做的事情,使用反射似乎不是一个好的设计.最好使用Map< String,Integer>例如:
static final Map VALUES_BY_NAME;
static {
final Map valuesByName = new HashMap<>();
valuesByName.put("width", 5);
valuesByName.put("potato", 2);
VALUES_BY_NAME = Collections.unmodifiableMap(valuesByName);
}
或者使用Guava:
static final ImmutableMap 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,variables,reflection,string
来源: https://codeday.me/bug/20190916/1807438.html