假设我想将这些键的潜在键和潜在值存储为常量。我怎样才能做到这一点?或者我应该完全避免它?
这是我对自己的看法,但正如你所能看到的那样,它有明显的垮台。
public static class Foo {
public static final String KEY = "foo" ;
public static class Values {
public static final String BAR = "bar" ;
public static final String HEY = "hey" ;
}
}
public static class Another {
public static final String KEY = "another" ;
public static class Values {
public static final String ONE = "1" ;
public static final String TWO = "two" ;
public static final String THREE = "THREE" ;
}
}
这允许我像这样访问这些键
miscellaneousMethod( Foo.KEY, Foo.Values.BAR )
miscellaneousMethod( Another.KEY, Another.Values.TWO )
但是,我并不想为每个键/可能值对编写单独的静态内部类。
有没有更好的方法将键值对存储为常量?
我想将它们存储为常量,以便稍后与生成的哈希映射进行比较。所以我可以问这样的事情:
if( map.get( Foo.KEY ).equals( Foo.Values.HEY ) ) { /* do stuff */ }
答案 0 :(得分:5)
如果它们都是常量,您可以使用枚举:
public enum ValueEnum {
FOO("foo", "bar", "hey"),
ANOTHER("another", "1", "two", "THREE"),
;
private final String key;
private final Set<String> values;
private ValueEnum(String key, String... values) {
this.key = key;
this.values = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(values)));
}
public final boolean isInMap(Map<String,String> map) {
if(map.containsKey(key)) {
return values.contains(map.get(key));
}
else {
return false;
}
}
}
然后
if( ValueEnum.FOO.isInMap(map) ) { /* do stuff */ }
答案 1 :(得分:2)
请避免这样的常数。对于常量,请使用Java枚举类型。它在引擎盖下编译为类,因此您可以获得类型安全性,并且您也可以在switch语句中使用它们。很高兴能够向他们添加方法。
这里有一个很好的例子: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
更长时间的讨论(有很多例子)在这里: http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html
答案 2 :(得分:0)
如果可能,您是否可以只在XML文件中指定这些键并使用Java XML绑定(JAXB)来加载它们。
答案 3 :(得分:-1)
将常量放在Map
中,然后使用方法Collections.unmodifiableMap()
使其不可修改。