简体   繁体   中英

Can I pass Class as enum's constructor parameter and then use it as return type in method?

My goal is to make method like this:

Map<String, Object> dataMap = new HashMap<>();

public ClassThatIsPassedToEnum someGetterMethod(MyEnum en){
   String key = en.keyInMap;
   Class<?> clazz = en.type;
   Object value = dataMap.get(key);
   //this method should return 'value' but casted to type from my enum
}

and the enum looks like this

enum MyEnum{
    EXAMP("example", Boolean.class);

    String keyInMap;
    Class<?> type;

    MyEnum(String keyInMap, Class<?> type){
        this.keyInMap = keyInMap;
        this.type = type;
    }
}

and then do this:

Boolean v = someGetterMethod(MyEnum.EXAMP);

Is it possible in java?

You can't do it with an enum.

But you can do it with a non-publicly instantiable class.

class MyNotEnum<T> {
    static final MyNotEnum EXAMP = new MyNotEnum<>("example", Boolean.class);

    String keyInMap;
    Class<T> type;

    private MyEnum(String keyInMap, Class<T> type){
        this.keyInMap = keyInMap;
        this.type = type;
    }
}

Actually, enum values are just static final fields inside the enum class. You get a few other things for free (like the valueOf method, resistance to reflective instantiation etc), but this is most of what there is to an enum. By doing it yourself, you get the opportunity to add differing generic types between the values.

Then:

public <T> T someGetterMethod(MyNotEnum<T> en){
   String key = en.keyInMap;
   Class<T> clazz = en.type;
   Object value = dataMap.get(key);
   return clazz.cast(value);
}

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