Java EnumSet Create fromString(Class enumType, String value)

Here you can find the source of fromString(Class enumType, String value)

Description

from String

License

Open Source License

Parameter

Parameter Description
enumType the type of enum
value a space separated list of enum value strings
E the enum type

Return

a set of enum values

Declaration

public static <E extends Enum<E>> Set<E> fromString(Class<E> enumType, String value) 

Method Source Code

//package com.java2s;
/******************************************************************************* 
 * Copyright (c) 2013 Red Hat, Inc. //w  w  w.  j  ava  2 s  .co m
 *  All rights reserved. 
 * This program is made available under the terms of the 
 * Eclipse Public License v1.0 which accompanies this distribution, 
 * and is available at http://www.eclipse.org/legal/epl-v10.html 
 * 
 * Contributors: 
 * Red Hat, Inc. - initial API and implementation 
 *
 ******************************************************************************/

import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class Main {
    /**
     * @param enumType the type of enum
     * @param value a space separated list of enum value strings
     * @param <E> the enum type
     * @return a set of enum values
     */
    public static <E extends Enum<E>> Set<E> fromString(Class<E> enumType, String value) {
        final Set<E> enumValues = new HashSet<E>();
        final StringTokenizer tokens = value == null ? null : new StringTokenizer(value);
        if (tokens == null || !tokens.hasMoreTokens()) {
            return EnumSet.noneOf(enumType);
        }
        for (; tokens.hasMoreTokens();) {
            try {
                final E enumValue = Enum.valueOf(enumType, tokens.nextToken());
                if (enumValue != null) {
                    enumValues.add(enumValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return enumValues.isEmpty() ? null : EnumSet.copyOf(enumValues);
    }
}

Related

  1. asSet(E[] array)
  2. createEnumSet(Class elementType)
  3. enumFromSet(EnumSet theSet)
  4. enumSet(T... elements)
  5. enumSetOf(long bitSet, Class eClass)
  6. fromString(Class enumClass, String name)
  7. intToEnumSet(Class enumClass, int decoded)
  8. newEnumSet(Class klass)
  9. noneOf( Class elementType)