Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:org.qi4j.runtime.types.EnumType.java

@Override
public Object fromQueryParameter(String parameter, Module module) throws IllegalArgumentException {
    try {/*  w  w  w  . j a  v  a  2s  . c  o  m*/
        Class enumType = module.classLoader().loadClass(type().name());

        // Get enum value
        return Enum.valueOf(enumType, parameter);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.github.dozermapper.core.converters.EnumConverter.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object convert(Class destClass, Object srcObj) {
    if (null == srcObj) {
        MappingUtils.throwMappingException("Cannot convert null to enum of type " + destClass);
    }//from  ww  w . j a  v a  2 s  . c o  m

    try {
        if ((srcObj.getClass().equals(Byte.class)) || (srcObj.getClass().equals(Byte.TYPE))) {
            return EnumUtils.getEnumList(destClass).get(((Byte) srcObj).intValue());
        } else if ((srcObj.getClass().equals(Short.class)) || (srcObj.getClass().equals(Short.TYPE))) {
            return EnumUtils.getEnumList(destClass).get(((Short) srcObj).intValue());
        } else if ((srcObj.getClass().equals(Integer.class)) || (srcObj.getClass().equals(Integer.TYPE))) {
            return EnumUtils.getEnumList(destClass).get((Integer) srcObj);
        } else if ((srcObj.getClass().equals(Long.class)) || (srcObj.getClass().equals(Long.TYPE))) {
            return EnumUtils.getEnumList(destClass).get(((Long) srcObj).intValue());
        } else {
            return Enum.valueOf(destClass, srcObj.toString());
        }
    } catch (Exception e) {
        MappingUtils.throwMappingException("Cannot convert [" + srcObj + "] to enum of type " + destClass, e);
    }
    return srcObj;
}

From source file:com.github.steveash.typedconfig.resolver.type.simple.EnumValueResolverFactory.java

@Override
public ValueResolver makeForThis(final ConfigBinding binding, final HierarchicalConfiguration config,
        ConfigFactoryContext context) {//from   w w  w .  j  a v a2s . co m

    final Class enumType = binding.getDataType().getRawType();
    final String key = binding.getConfigKeyToLookup();
    return new ValueResolver() {
        @Override
        public Object resolve() {
            String enumLabel = config.getString(binding.getConfigKeyToLookup(), null);
            if (StringUtils.isBlank(enumLabel))
                return null;

            return resolveEnumInstance(enumLabel);
        }

        private Object resolveEnumInstance(String enumLabel) {
            try {
                return Enum.valueOf(enumType, enumLabel);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("The value of the configuration key " + key + " is "
                        + enumLabel + " which is not a member of the enum " + enumType.getName(), e);
            }
        }

        @Override
        public Object convertDefaultValue(String defaultValue) {
            return resolveEnumInstance(defaultValue);
        }

        @Override
        public String configurationKeyToLookup() {
            return key;
        }
    };
}

From source file:com.esofthead.mycollab.schedule.email.format.I18nFieldFormat.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from  w w w. ja v a  2 s.  c o m
public String formatField(MailContext<?> context) {
    Object wrappedBean = context.getWrappedBean();
    Object value = null;
    try {
        value = PropertyUtils.getProperty(wrappedBean, fieldName);
        if (value == null) {
            return new Span().write();
        } else {
            Enum valueEnum = Enum.valueOf(enumKey, value.toString());
            return new Span().appendText(LocalizationHelper.getMessage(context.getLocale(), valueEnum)).write();
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Can not generate of object " + BeanUtility.printBeanObj(wrappedBean) + " field: " + fieldName
                + " and " + value, e);
        return new Span().write();
    }
}

From source file:org.diffkit.util.DKStringUtil.java

/**
 * assumes comma separator/*from w  ww .  j  a  va  2s  . c om*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<?> parseEnumList(String target_, Class enumClass_) {
    if (target_ == null)
        return null;
    String[] elements = target_.split(",");
    if (ArrayUtils.isEmpty(elements))
        return null;
    List<Enum> values = new ArrayList<Enum>(elements.length);
    for (String element : elements) {
        element = StringUtils.trimToNull(element);
        if (element == null)
            continue;
        values.add(Enum.valueOf(enumClass_, element));
    }
    return values;
}

From source file:com.im.web.base.PropertyFilter.java

/**
 * @param filterName ,???. //from  ww w  .j av  a 2  s.c  o  m
 *                   eg. LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final String value) {

    String firstPart = StringUtils.substringBefore(filterName, "_");
    String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
    String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());

    try {
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    //      Assert.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter??" + filterName + ",??.");
    propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    //      this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
}

From source file:org.metawidget.example.struts.addressbook.converter.EnumConverter.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object convert(Class clazz, Object value) {

    if (value == null || "".equals(value)) {
        return null;
    }/*w w w. j ava 2  s.  c o  m*/

    return Enum.valueOf((Class<Enum>) clazz, (String) value);
}

From source file:io.gravitee.management.rest.mapper.ObjectMapperResolver.java

public ObjectMapperResolver() {
    mapper = new GraviteeMapper();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override/*  ww  w. ja v a2  s. com*/
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type,
                BeanDescription beanDesc, final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
}

From source file:edu.utah.further.core.api.discrete.EnumUtil.java

/**
 * Returns the enum constant of the specified enum type with the specified name. The
 * name must match exactly an identifier used to declare an enum constant in this
 * type. If it does not, this method returns <code>null</code>.
 *
 * @param enumType/*from   w  ww . jav  a2s.  c o  m*/
 *            the Class object of the enum type from which to return a constant
 * @param name
 *            the name of the constant to return
 * @return the enum constant of the specified enum type with the specified name or
 *         <code>null</code> if not found
 * @see {link Enum.valueOf}
 */
public static <E extends Enum<E>> E valueOfNullSafe(final Class<E> enumType, final String name) {
    try {
        return Enum.valueOf(enumType, name);
    } catch (final IllegalArgumentException e) {
        return null;
    } catch (final NullPointerException e) {
        return null;
    }
}

From source file:technology.tikal.customers.dao.objectify.CustomerDaoOfy.java

@Override
public List<CustomerOfy> consultarTodos(CustomerFilter filtro, PaginationDataDual<Long, String> pagination) {
    NamePriorityFilterValues namePriority;
    try {/*from www .  j  a  v a 2s.c  o m*/
        namePriority = Enum.valueOf(NamePriorityFilterValues.class, filtro.getIndex());
    } catch (IllegalArgumentException ex) {
        throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                new String[] { "IllegalIndex.CustomerDaoOfy.consultarTodos" },
                new String[] { filtro.getIndex() }, "Invalid Index"));
    }
    String indexOfy = "normalized" + filtro.getIndex();
    if (namePriority != NamePriorityFilterValues.Name) {
        indexOfy = "name." + indexOfy;
    }
    return paginatorDelegate.consultarTodosTemplate(
            new PaginationContext<Object>(indexOfy, filtro.getIndex(), filtro, pagination));
}