2

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);
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, i forgot to change "" to strCsv.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.