Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with enum key and different value types

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?

like image 298
Marcin Nowak Avatar asked Nov 01 '22 06:11

Marcin Nowak


1 Answers

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));
}
like image 88
xerx593 Avatar answered Nov 09 '22 12:11

xerx593