[英]Can I pass Class as enum's constructor parameter and then use it as return type in method?
我的目标是制作这样的方法:
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
}
枚举看起来像这样
enum MyEnum{
EXAMP("example", Boolean.class);
String keyInMap;
Class<?> type;
MyEnum(String keyInMap, Class<?> type){
this.keyInMap = keyInMap;
this.type = type;
}
}
然后这样做:
Boolean v = someGetterMethod(MyEnum.EXAMP);
java 有可能吗?
你不能用枚举来做到这一点。
但是您可以使用非公开实例化的 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;
}
}
实际上,枚举值只是枚举 class 内的 static 最终字段。 您可以免费获得其他一些东西(例如valueOf
方法、对反射实例化的抵抗等),但这是枚举的大部分内容。 通过自己做,您有机会在值之间添加不同的泛型类型。
然后:
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.