我希望能够通过编程为每个键指定一个键和允许值的列表,以便在编译时检查代码是否有错误,并希望获得更好的性能。
想象一下,我在数据库中表示单词,每个单词都有许多功能:
public class Word {
public Map<Feature, FeatureValue> features = new EnumMap<Feature, FeatureValue>();
}
我有一个枚举类:
public enum Feature {
TYPE("Type") {
enum Value {
NOUN("Noun"),
VERB("Verb");
}
@Override
public Value[] getValues() {
return new Value[]{Value.NOUN, Value.VERB};
}
},
PLURALITY("Plurality") {
enum Value {
SING("Singular"),
PL("Plural");
}
@Override
public Value[] getValues() {
return new Value[]{Value.SING, Value.PL};
}
},
}
我至少想做一些事情,比如:
word.features.put(TYPE,TYPE.Value.NOUN);word.features.put(PLURALITY,PLURALITY.Value.PL);
因此,很容易看到值与键匹配,但似乎不允许使用枚举语法中的枚举。
我也试过这个:
TYPE("Type") {
public String NOUN = "Noun";
public String VERB = "Verb";
但我不能引用TYPE.NOUN,因为出于某种原因,它们不允许是静态的。
请问有没有人知道指定这样的东西的好模式?我只是担心如果在我的代码中使用字符串,比如
word.features.put(TYPE, "Noun");
我正在询问打字错误等方面的问题。
你不能那样做,但你可以这样做:
// define a type values as an enum:
enum TypeValue {
Noun, Verb
}
// define an attribute class parametrized by an enum:
public class Attribute<E extends Enum<E>> {
// define your attribute types as static fields inside this class
public static Attribute<TypeValue> Type = new Attribute<TypeValue>();
}
// and now define your method like this:
<E extends Enum<E>, Feature extends Attribute<E>> void put(Feature feature, E value) {
}
// you will then have a compilation error when trying to invoke the method with improper associated parameters.
// eg if we define
enum OtherValue { X }
features.put(Attribute.Type, TypeValue.Noun); // ok
features.put(Attribute.Type, OtherValue.X); // Fails