对于你在这里所做的事情,使用反射似乎不是一个好的设计.最好使用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);
}
}