[英]Pass a generic enum with custom implemented methods as a parameter
I'd like to map the Label -> Value of a generic enum instance.我想映射通用枚举实例的 Label -> Value。 This is feasible with this code:这段代码是可行的:
public static <T extends Enum<T>> List<Map<String, String>> mapEnumValues(T[] myEnumValues) {
List<Map<String, String>> list = new ArrayList<>();
for (T myEnumValue : myEnumValues) {
Map<String, String> map = new HashMap<>();
map.put("label", myEnumValue.name());
map.put("value", myEnumValue.toString());
list.add(map);
}
return list;
}
But now I want to use another key for the map, which is for instance a method getLabel()
implemented by every one of my enums.但是现在我想为地图使用另一个键,例如,我的每个枚举都实现了一个方法getLabel()
。 For example, given:例如,给定:
public interface Labelizable{
public String getLabel();
}
static public enum Options implements Labelizable {
option01("Option 01", 1), option02("Option 02", 2)
... constructor, getLabel(), ....
So I'd like to replace that row of code with:所以我想用以下代码替换该行代码:
map.put("label", myEnumValue.getLabel()); // instead of .name()
In order to do that I should declare something on the signature thst forces the parameter to be an enum that implements the getLabel()
method.为了做到这一点,我应该在签名上声明一些东西 thst 强制参数是一个实现getLabel()
方法的枚举。 I tried, for example,我试过,例如,
public static <T extends Enum<T implements Labelizable>>
and some other syntax like this with no success.和其他一些像这样的语法没有成功。 Is there any way to achieve this behaviour, or the fact that enums can't inherit prevent such a method?有没有办法实现这种行为,或者枚举不能继承的事实阻止了这种方法?
The syntax is:语法是:
public static <T extends Enum<T> & Labelizable>
List<Map<String, String>> mapEnumValues(T[] myEnumValues) {
You put the superclass that your generic parameter has to inherit first, then the interfaces that it has to implement, all separated by &
.您首先放置泛型参数必须继承的超类,然后是它必须实现的接口,全部以&
分隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.