[英]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? java 有可能吗?
You can't do it with an enum.你不能用枚举来做到这一点。
But you can do it with a non-publicly instantiable class.但是您可以使用非公开实例化的 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.实际上,枚举值只是枚举 class 内的 static 最终字段。 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.您可以免费获得其他一些东西(例如valueOf
方法、对反射实例化的抵抗等),但这是枚举的大部分内容。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.