문제

I'd like to serialise some EnumSet<FooType> to String using its toString() method.

E.g.: EnumSet.of(FooType.COMMON, FooType.MEDIUM).toString() will give [COMMON, MEDIUM].

The question is about an elegant way to deserialise such a string back to the EnumSet<FooSet>. I'm looking for some commonly known library (may be like apache-commons) or a standard Util-class for such things.

Something like: EnumSetUtil.valueOf(FooType.class, "[COMMON, MEDIUM]")

I've implemented this thing in such way:

public static <E extends Enum<E>> EnumSet<E> valueOf(Class<E> eClass, String str) {
    String[] arr = str.substring(1, str.length() - 1).split(",");
    EnumSet<E> set = EnumSet.noneOf(eClass);
    for (String e : arr) set.add(E.valueOf(eClass, e.trim()));
    return set;
}

But, may be there is a ready solution, or a dramatically easy way for doing this.

도움이 되었습니까?

해결책

With Java 8 you can do something like this with Lambda expressions and streams:

EnumSet.copyOf(Arrays.asList(str.split(","))
.stream().map(FooType::valueOf).collect(Collectors.toList()))

다른 팁

With guava 19.0:

    Iterable<String> i = Splitter.on(",")
        .trimResults(CharMatcher.WHITESPACE.or(CharMatcher.anyOf("[]")))
        .split(str);
    Set<YourEnum> result = FluentIterable.from(i)
        .transform(Enums.stringConverter(YourEnum.class)).toSet();

OR another way with JSON library if you can accept String format like this ['COMMON', 'MEDIUM'].

Using Gson ('com.google.code.gson:gson:2.3.1') library you can do:

public static EnumSet getEnumObject(Type type, String jsonStrToDeserialize) {
    Gson gson = new Gson();
    return jsonStrToDeserialize == null ? null : (EnumSet) gson.fromJson(jsonStrToDeserialize, type);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top