map を直接使用することは避けたいと思います。あなたが探しているのは、おそらくよりアプリケーション固有のものです。
あなたが構築しているもの全体が一連の設定用であると仮定します。「設定」には、事前定義されたキーのセットがあります。各キーは、特定の値の対応する設定値を受け入れるように事前定義されています。間違った型が指定された場合、例外がスローされます。
おおよそ次のようなものが合理的だと思います。
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() はジェネリックにすることができ、クラスを追加のパラメーターなどとして取ることができます。しかし、少なくとも、これは ua の出発点を与えるはずです。