我宁愿避免直接使用地图。您正在寻找的可能是更特定于应用程序的东西:
假设你正在构建的整个东西都是为了一堆设置。您的“设置”将有一组预定义的键。每个键都预先定义为接受特定值的相应设置值。如果提供了不正确的类型,将会抛出异常。
我认为大致这样的事情是合理的:
enum SettingValueType {
public boolean isCorrectType(Object obj) {
return true if obj is correct type represented by this enum
}
STRING, INT, FLOAT // add support to other type if u want
};
clsss SettingValue {
SettingValueType type;
Object value;
}
class SettingRepo { // a repository of setting entries
private Map<String, SettingValueType> allowedKeyAndType;
private Map<String, Object> settings;
SettingRepo() {
// setup allowedKeyAndType programmatically or from config etc, depends on your design
}
public SettingValue setSetting(String key, Object value) {
SettingValueType valueType = allowedKeyAndType.get(key);
if (valueType == null) {
throw new KeyNotAllowedException();
}
if (v!alueType.isCorrectType(value) {
throw new ValueIncorectTypeException();
}
return settings.put(key, new SettingValue(valueType, value));
}
}
public SettingValue getSetting(String key) {
// u may throw exception if key is not in predefined set
return settings.get(key);
}
// u may consider adding some convinient methods too:
public String setStringSetting(String key, String value) {
if alllowedKeyAndType do not contains key {
throw KeyNOtAllowedException
}
if type is not STRING {
throw IncorrectTypeExceptin
}
settings.put(key, new SettingValue(STRING, value))
}
public String getStringSetting(String key) {
// should be straight forward now, right?
}
}
有很多地方可以根据您的使用情况进行改进:如果您的类型非常动态,您可以将 SettingValueType 设置为一堆策略,或者直接使用 Class。setSetting() 可以通用化并将 Class 作为额外参数等。但至少,这应该给 ua 起点。