Reputation: 51
I would like to genericly convert String in csv form to List of enum. However java won't recognise the generic enum type.
I'm using Guava and can't use Java 8.
Any idea ?
public static <E extends Enum<E>> List<E> getEnumList(String csvLine) {
List<String> csvList = Arrays.asList(csvLine.split(","));
Function<String, E> enumList = new Function<String, E>() {
@Override
public E apply(String csvStr) {
return Enum.valueOf(E.class, csvStr);
}
};
return Lists.transform(csvList, enumList);
}
Upvotes: 2
Views: 1330
Reputation: 62864
You have to pass the Class<E>
, because E
will be erased (and replaced with something specific at Runtime).
Something like:
public static <E extends Enum<E>> List<E> getEnumList(String csvLine, Class<E> clazz) {
List<String> csvList = Arrays.asList(csvLine.split(","));
Function<String, E> enumList = new Function<String, E>() {
@Override
public E apply(String csvStr) {
return Enum.valueOf(clazz, "");
}
};
return Lists.transform(csvList, enumList);
}
As a side note, I guess you have to replace the empty string ""
with csvStr
, otherwise the csvStr
parameter doesn't make any sense.
Upvotes: 3