如何将枚举类型存储到地图中? [英] How do I store Enum types into a map?
问题描述
在伪代码中,它看起来像这样:
枚举MyType {VAL1,VAL2};
枚举MyColors {BLUE,RED};
映射< String,Class> map = Maps.newHashMap();
map.put(key1,MyType.class); //这是MyType枚举以上
map.put(colors,MyColors.class); //这是MyColors枚举以上
...
String inputType =colors;
String inputValue =BLUE;
类c = map.get(inputType);
assertEquals(MyColors.BLUE,c.ValueOf(inputValue)); //这里我想要MyColors.ValueOf()来调用
Class c2 = map.get(key1);
assertEquals(MyType.VAL1,c.ValueOf(VAL1)); //这里我想要MyType.ValueOf()来调用
我该怎么做? p>
为了给我一些背景,为什么我这样做 - 我有多个这样的枚举类型,我得到一个输入,告诉我什么样的枚举(在文本中)和一个的枚举值,所以我想从地图中查找枚举类,然后调用正确解析的静态ValueOf。
注 - 我不想在地图中存储MyType对象,我想存储类引用
谢谢!
您可以使用 java.lang.Enum.valueOf(Class enumType,String name)
枚举MyType {VAL1,VAL2};
映射enumMap = Maps.newHashMap();
map.put(key1,MyType.class);
...
类c = map.get(key1);
assertEquals(MyType.VAL1,Enum.valueOf(c,VAL1));
I am trying to store and retrieve an enum class so I can later find the correct type (based on configuration) and call ValueOf on it to parse a string. How do I put/get and then call the ValueOf?
In pseudo code it would look something like this:
enum MyType { VAL1, VAL2 };
enum MyColors { BLUE, RED };
Map<String, Class> map = Maps.newHashMap();
map.put("key1", MyType.class); //this is the MyType enum above
map.put("colors", MyColors.class); //this is the MyColors enum above
...
String inputType = "colors";
String inputValue = "BLUE";
Class c = map.get(inputType);
assertEquals(MyColors.BLUE, c.ValueOf(inputValue)); //here I want MyColors.ValueOf() to get called
Class c2 = map.get("key1");
assertEquals(MyType.VAL1, c.ValueOf("VAL1")); //here I want MyType.ValueOf() to get called
How can I do this?
To give some background on why I am doing this - I have multiple such enum types and I get an input which tells me what kind of enum it is (in text) and one of the values from the enum, so I want to look up the enum class from the map and then call the static ValueOf on it which will parse correctly.
Note - I do not want to store MyType objects in the map, I want to store class references
Thanks!
You can use java.lang.Enum.valueOf(Class enumType, String name)
enum MyType { VAL1, VAL2 };
Map enumMap = Maps.newHashMap();
map.put("key1", MyType.class);
...
Class c = map.get("key1");
assertEquals(MyType.VAL1, Enum.valueOf(c, "VAL1"));
这篇关于如何将枚举类型存储到地图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!