使用枚举键和不同的值类型映射 [英] Map with enum key and different value types
本文介绍了使用枚举键和不同的值类型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用Java定义映射,哪些键是枚举,哪些类型的值取决于键。例如,假设我们有以下枚举类型:
pre $ enum KeyType {
HEIGHT(Integer.class),
NAME(String.class),
WEIGHT(Double.class)
//类构造函数和getter字段
}
$ c $
地图< / pre>
KeyType,Object> map = new EnumMap<>(KeyType.class);
是否有任何简单且安全的方法来编写泛型方法:
public < T> T get(KeyType键){
// ...
}
那会从该映射中获取值并将其转换为与类型对应的值?
解决方案
UPDATE !!!:
考虑到这一点:
enum KeyType {
//您的枚举...
私人最终Class val;
//构造函数...
//通用(!)访问类字段:
< T>类< T> val(){
return val;
$ / code $ / pre
...这是可能的:
public< T> T get(KeyType key){
return(T)key.val()。cast(map.get(key));
}
I want to define map in Java, which keys are enums, and types of value depend of key. For example, suppose that we have following enum type:
enum KeyType {
HEIGHT(Integer.class),
NAME(String.class),
WEIGHT(Double.class)
// constructor and getter for Class field
}
and some map:
Map< KeyType, Object > map = new EnumMap<>(KeyType.class);
Is there any simple and safe way to write generic method:
public < T > T get(KeyType key) {
//...
}
that would get value from that map and cast it to corresponding with type class?
解决方案 UPDATE!!!:
With this in mind:
enum KeyType {
//your enums ...
private final Class val;
//constructor ...
//and generic(!) access to the class field:
<T> Class<T> val() {
return val;
}
}
...this is possible:
public <T> T get(KeyType key) {
return (T) key.val().cast(map.get(key));
}
这篇关于使用枚举键和不同的值类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文