Example usage for java.lang Class getEnumConstants

List of usage examples for java.lang Class getEnumConstants

Introduction

In this page you can find the example usage for java.lang Class getEnumConstants.

Prototype

public T[] getEnumConstants() 

Source Link

Document

Returns the elements of this enum class or null if this Class object does not represent an enum type.

Usage

From source file:com.sunchenbin.store.feilong.core.lang.EnumUtil.java

/**
 * fieldName value ./*from w  ww .  j  a  va  2 s.c o m*/
 * 
 * <pre>
 * 
 * ?{@link HttpMethodType} ,?:
 * 
 * {@code
 *  EnumUtil.getEnumByField(HttpMethodType.class, "method", "get")
 * }
 * </pre>
 *
 * @param <E>
 *            the element type
 * @param <T>
 *            the generic type
 * @param enumClass
 *            the enum class  {@link HttpMethodType}
 * @param propertyName
 *            ??, {@link HttpMethodType}method,javabean 
 * @param specifiedValue
 *             post
 * @param ignoreCase
 *            ??
 * @return  enum constant
 * @see com.sunchenbin.store.feilong.core.bean.BeanUtil#getProperty(Object, String)
 * @since 1.0.8
 */
private static <E extends Enum<?>, T> E getEnumByPropertyValue(Class<E> enumClass, String propertyName,
        T specifiedValue, boolean ignoreCase) {

    if (Validator.isNullOrEmpty(enumClass)) {
        throw new IllegalArgumentException("enumClass is null or empty!");
    }

    if (Validator.isNullOrEmpty(propertyName)) {
        throw new IllegalArgumentException("the fieldName is null or empty!");
    }

    // An enum is a kind of class
    // An annotation is a kind of interface
    //  Class ?, null.
    E[] enumConstants = enumClass.getEnumConstants();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("enumClass:[{}],enumConstants:{}", enumClass.getCanonicalName(),
                JsonUtil.format(enumConstants));
    }
    for (E e : enumConstants) {
        Object propertyValue = PropertyUtil.getProperty(e, propertyName);
        if (isEquals(propertyValue, specifiedValue, ignoreCase)) {
            return e;
        }
    }
    String messagePattern = "can not found the enum constants,enumClass:[{}],propertyName:[{}],value:[{}],ignoreCase:[{}]";
    throw new BeanUtilException(
            Slf4jUtil.formatMessage(messagePattern, enumClass, propertyName, specifiedValue, ignoreCase));
}

From source file:org.jtester.utility.ReflectionUtils.java

/**
 * Gets the enum value that has the given name.
 * //from   w ww .  j a va  2s  . c  o m
 * @param enumClass
 *            The enum class, not null
 * @param enumValueName
 *            The name of the enum value, not null
 * @return The actual enum value, not null
 * @throws JTesterException
 *             if no value could be found with the given name
 */
public static <T extends Enum<?>> T getEnumValue(Class<T> enumClass, String enumValueName) {
    T[] enumValues = enumClass.getEnumConstants();
    for (T enumValue : enumValues) {
        if (enumValueName.equalsIgnoreCase(enumValue.name())) {

            return enumValue;
        }
    }
    throw new JTesterException(
            "Unable to find a enum value in enum: " + enumClass + ", with value name: " + enumValueName);
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 *
 * @param <E>//from w  w w .  j  av  a2  s . co m
 * @param value
 * @param enumClass
 * @return
 */
public static <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
    for (E e : enumClass.getEnumConstants()) {
        if (e.name().equals(value)) {
            return true;
        }
    }
    return false;
}

From source file:org.erdc.cobie.shared.COBieUtility.java

public static <T extends Enum<T>> List<String> getEnumLiteralsAsStringList(Class<T> enumClass) {
    ArrayList<String> names = null;
    try {//from w  ww  .  j a v a 2 s. co  m
        T[] items = enumClass.getEnumConstants();
        Method accessor = enumClass.getMethod("getDisplayValue");

        names = new ArrayList<String>(items.length);
        for (T item : items) {
            names.add(accessor.invoke(item).toString());
        }

    } catch (NoSuchMethodException ex) {

    } catch (InvocationTargetException ex) {

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return names;
}

From source file:com.feilong.commons.core.lang.EnumUtil.java

/**
 * fieldName value <br>/*ww  w. j a va  2s  .  co m*/
 * 
 * <pre>
 * 
 * ?{@link HttpMethodType} ,?:
 * 
 * {@code
 *    EnumUtil.getEnumByField(HttpMethodType.class, "method", "get")
 * }
 * </pre>
 *
 * @param <E>
 *            the element type
 * @param <T>
 *            the generic type
 * @param enumClass
 *            the enum class  {@link HttpMethodType}
 * @param propertyName
 *            ??, {@link HttpMethodType}method,javabean 
 * @param value
 *             post
 * @param ignoreCase
 *            ??
 * @return  enum constant
 * @throws IllegalArgumentException
 *             if Validator.isNullOrEmpty(enumClass) or Validator.isNullOrEmpty(propertyName)
 * @throws NoSuchFieldException
 *             ??
 * @throws BeanUtilException
 *             the bean util exception
 * @see com.feilong.commons.core.bean.BeanUtil#getProperty(Object, String)
 * @since 1.0.8
 */
private static <E extends Enum<?>, T> E getEnumByPropertyValue(Class<E> enumClass, String propertyName, T value,
        boolean ignoreCase) throws IllegalArgumentException, NoSuchFieldException, BeanUtilException {

    if (Validator.isNullOrEmpty(enumClass)) {
        throw new IllegalArgumentException("enumClass is null or empty!");
    }

    if (Validator.isNullOrEmpty(propertyName)) {
        throw new IllegalArgumentException("the fieldName is null or empty!");
    }

    // An enum is a kind of class
    // and an annotation is a kind of interface
    //  Class ? null.
    E[] enumConstants = enumClass.getEnumConstants();

    for (E e : enumConstants) {
        if (log.isDebugEnabled()) {
            log.debug("e:{}", JsonUtil.format(e));
        }

        Object propertyValue = PropertyUtil.getProperty(e, propertyName);

        if (null == propertyValue && null == value) {
            return e;
        }
        if (null != propertyValue && null != value) {
            if (ignoreCase && propertyValue.toString().equalsIgnoreCase(value.toString())) {
                return e;
            } else if (propertyValue.equals(value)) {
                return e;
            }
        }
    }

    throw new NoSuchFieldException("can not found the enum constants,enumClass:[" + enumClass
            + "],propertyName:[" + propertyName + "],value:[" + value + "],ignoreCase:[" + ignoreCase + "]");
}

From source file:org.unitils.util.ReflectionUtils.java

/**
 * Gets the enum value that has the given name.
 * // w w  w.  j ava 2  s . co  m
 * @param enumClass
 *            The enum class, not null
 * @param enumValueName
 *            The name of the enum value, not null
 * @return The actual enum value, not null
 * @throws UnitilsException
 *             if no value could be found with the given name
 */
public static <T extends Enum<?>> T getEnumValue(Class<T> enumClass, String enumValueName) {
    T[] enumValues = enumClass.getEnumConstants();
    for (T enumValue : enumValues) {
        if (enumValueName.equalsIgnoreCase(enumValue.name())) {

            return enumValue;
        }
    }
    throw new UnitilsException(
            "Unable to find a enum value in enum: " + enumClass + ", with value name: " + enumValueName);
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

@SuppressWarnings("unchecked")
// used in hibernate.jsp
public static String getDisplayString(Type hibernateType) {
    if (hibernateType instanceof EntityType) {
        return hibernateType.getName() + " (enter integer of ID / primary key field)";
    } else if (hibernateType instanceof CustomType) {
        if (Enum.class.isAssignableFrom(hibernateType.getReturnedClass())) {
            Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) hibernateType.getReturnedClass();
            StringBuilder result = new StringBuilder();
            result.append(enumClass.getName());
            result.append(" (");
            boolean first = true;
            for (Enum<?> nextEnum : enumClass.getEnumConstants()) {
                if (!first) {
                    result.append(" | ");
                } else {
                    first = false;/* w  ww  .j  a va 2 s  . c  om*/
                }
                result.append(nextEnum.name());
            }
            result.append(")");
            return result.toString();
        }
    }
    return hibernateType == null ? "" : hibernateType.getName();
}

From source file:com.all.shared.sync.SyncGenericConverter.java

private static Object readValue(String attributeName, Class<?> clazz, Map<String, Object> map)
        throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    Object value = map.get(attributeName);
    if (value != null && !clazz.equals(value.getClass())) {
        if (clazz.equals(Date.class) && StringUtils.isNumeric(value.toString())) {
            return new Date(new Long(value.toString()));
        }//from   www . j  ava2  s.  com
        if (clazz.isEnum() && value instanceof String) {
            for (Object enumType : clazz.getEnumConstants()) {
                if (value.equals(enumType.toString())) {
                    return enumType;
                }
            }
        }
        if (PRIMITIVES.contains(clazz)) {
            return clazz.getConstructor(String.class).newInstance(value.toString());
        }
    }
    return value;
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Coerce object type.//from  www .  j  a  va 2s.c  o  m
 * 
 * @param <T>
 *            the expected type
 * @param from
 *            from object
 * @param expectedType
 *            to object type
 * @return the to object
 */
public static <T> T coerceType(Object from, Class<? extends T> expectedType) {
    if (from == null) {
        return null;
    }
    Object targetValue = null;
    if (expectedType.isInstance(from)) {
        targetValue = from;
    } else if (expectedType.isEnum()) {
        for (Object e : expectedType.getEnumConstants()) {
            if (from.toString().equalsIgnoreCase(e.toString())) {
                targetValue = e;
                break;
            }
        }
        if (targetValue == null) {
            throw new PaxmlRuntimeException(
                    "No enum named '" + from + "' is defined in class: " + expectedType);
        }
    } else if (List.class.equals(expectedType)) {
        targetValue = new ArrayList();
        collect(from, (Collection) targetValue, true);
    } else if (Set.class.equals(expectedType)) {
        targetValue = new LinkedHashSet();
        collect(from, (Collection) targetValue, true);
    } else if (isImplementingClass(expectedType, Collection.class, false)) {
        try {
            targetValue = expectedType.newInstance();
        } catch (Exception e) {
            throw new PaxmlRuntimeException(e);
        }
        collect(from, (Collection) targetValue, true);
    } else if (Iterator.class.equals(expectedType)) {
        List list = new ArrayList();
        collect(from, list, true);
        targetValue = list.iterator();
    } else if (isImplementingClass(expectedType, Coerceable.class, false)) {

        try {
            Constructor c = expectedType.getConstructor(Object.class);
            targetValue = c.newInstance(from);
        } catch (Exception e) {
            throw new PaxmlRuntimeException(e);
        }
    } else if (from instanceof Map) {
        return mapToBean((Map) from, expectedType);
    } else {
        targetValue = ConvertUtils.convert(from.toString(), expectedType);
    }

    return (T) targetValue;
}

From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java

/**
 * Retrieves a message from a resource bundle from its key.
 * <p>//from   w ww.ja va  2  s. com
 * @param key Resource key to retrieve.
 * @param parameters Parameters to inject while formatting the message.
 * @return The formatted message.
 */
@SuppressWarnings("nls")
private static final String retrieve(final Enum<? extends IBundle> key, final Object... parameters) {
    if (!isInitialized) {
        initialize();
    }

    final Class<? extends IBundle> bundleClass = key.getDeclaringClass();

    if (BUNDLES.containsKey(bundleClass)) {
        try {
            return MessageFormat.format(BUNDLES.get(bundleClass).getString(((IBundle) key).getKey()),
                    parameters);
        } catch (MissingResourceException e) {
            throw new ResourceBundleException(BundleAthenaBase.ResourceBundleInvalidKey,
                    bundleClass.getSimpleName(), key.name(), bundleClass.getEnumConstants()[0].getKey(),
                    getLocale(), e);
        }
    }

    return "Resource bundle key cannot be found [bundle=" + bundleClass.getName() + ", key=" + key.name() + "]";
}