Generic Enums in Java

I have a base configuration class that provides all possible keys and the type of the corresponding value types in an enumeration, for example:

public class Configuration {
    public static enum Key {
        FIRST_KEY("actual key 1", Long.class),
        ANOTHER_KEY("actual key 2", Integer.class)

        public final String value;
        public final Class type;

        Key(String value, Class type) {
            this.value = value;
            this.type = type;
        }
    }
}

What I would like to do is write a method that parses the value of the given key from String and returns the value as the appropriate type. Mainly:

public <T> T getValue(Key<T> key, String valueStr);

This attempt failed in the method declaration, as a message appears stating that Enums in Java cannot have type arguments. Any ideas on how to achieve something like this?

+5
source share
5 answers

You could just

public <T> T getValue(Key key, String valueStr);

It has no compile time check, so it will pass the compilation

Short value = getValue(FIRST_KEY, string);  // should be Long

The best answer? Do not use enum! Make a Key<T>regular class.

public static class Key<T>
{
    public static final Key<Long> FIRST_KEY 
                  = new Key("actual key 1", Long.class);
    ...

    public final String value;
    public final Class<T> type;

    Key(String value, Class<T> type) {
        this.value = value;
        this.type = type;
    }
}
+3

getValue(), .

public <T> T getValue(Key k, Class<T> type);

, .

+2

Map < Class, String > .

Map<Class, Enum>, FIRST_KEY a get(objectParameter.getClass()), objectParameter

, Long : Map<Class, Set< Enum>> , .

0

enum :

public <T extends Enum> T getValue(key, Class<T extends Enum> enumClazz) {
    return enumClazz.cast(...);
}
-1

getType Enum, , .

getType() Enum.

 public Class getType()
 {      
    return type;    
 } 

getType() .

 public Object getValue(Key key , String strValue)
 {
    return key.getType().cast(strValue) ;   
 }

, IF, , , . Integer Integer.parseInt(s), ClassCastExcpetion

-1
source

All Articles