对于你在这里所做的事情,使用反射似乎不是一个好的设计。最好使用
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);}Or with Guava:
static final ImmutableMap<String, Integer> VALUES_BY_NAME = ImmutableMap.of( "width", 5, "potato", 2);
Or with an 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); }}


