简体   繁体   中英

How do I store Enum types into a map?

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"));

public enum MyType {
    VAL1("value1"),
    VAL2("value2");

    private valueString;

    private enum MyType(String val) {
        valueString = val;
    }

    @Override
    public String toString() {
        return valueString;
    }
}

It looks like you want to use the String as a key so define your MyType enum and then to set and get values:

Map<String, MyType> enumMap = new HashMap<String, MyType>();
enumMap.put("key", MyType.VAL1);

...

MyType keyVal = enumMap.get("key1");
String settingValue = keyVal.toString();  // will be "value1"

Instead of using Class as the second type, use your enum's type.

enum MyType { VAL1, VAL2 };

public static void main (String args[]){
    Map<String,MyType> map = new HashMap<String,MyType>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM