Example usage for java.lang.reflect Field isEnumConstant

List of usage examples for java.lang.reflect Field isEnumConstant

Introduction

In this page you can find the example usage for java.lang.reflect Field isEnumConstant.

Prototype

public boolean isEnumConstant() 

Source Link

Document

Returns true if this field represents an element of an enumerated type; returns false otherwise.

Usage

From source file:org.mule.modules.zuora.ZuoraModule.java

@MetaDataKeyRetriever
public List<MetaDataKey> getMetadataKeys() {
    List<MetaDataKey> keys = new ArrayList<MetaDataKey>();
    Class<?> c = ZObjectType.class;

    Field[] flds = c.getDeclaredFields();
    for (Field f : flds) {
        if (f.isEnumConstant()) {
            Object value = null;/*from w w  w.ja  v a 2 s  .  co m*/
            try {
                value = f.get(c);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Error while retrieving keys.", e);
            }
            keys.add(createKey(((ZObjectType) value).getZObjectClass()));
        }
    }

    return keys;
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Return where clause expression for non-String
 * {@code entityPath.fieldName} by transforming it to text before check its
 * value./*from   w  w  w. j a  va 2s .c o  m*/
 * <p/>
 * Expr:
 * {@code entityPath.fieldName.as(String.class) like ('%' + searchStr + '%')}
 * <p/>
 * Like operation is case insensitive.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @param enumClass Enumeration type. Needed to enumeration values
 * @return BooleanExpression
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> BooleanExpression createEnumExpression(PathBuilder<T> entityPath, String fieldName,
        String searchStr, Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}

From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java

/**
 * Returns the name of the fields that are enum constants according to reflection
 *
 * @return a non-null set of fields that are enum constants
 *///from ww w  .j  av a  2 s . c  om
private Set<String> enumConstantsNames(final Class enumClass) {
    final Set<String> enumConstantFieldNames = new HashSet<String>();

    for (final Field field : enumClass.getFields()) {
        if (field.isEnumConstant())
            enumConstantFieldNames.add(field.getName());
    }

    return enumConstantFieldNames;
}

From source file:org.commoncrawl.util.RPCStructIntrospector.java

public RPCStructIntrospector(Class classType) {
    theClass = classType;//from   w w  w . j  a v  a2 s  . c o m
    for (Field field : classType.getDeclaredFields()) {
        System.out.println("Found Field:" + field.getName());
        if (!field.isEnumConstant()) {
            propertyNames.add(field.getName());
        }
    }

    for (Method m : classType.getDeclaredMethods()) {
        System.out.println("Found Method:" + m.getName());
        if (m.getName().startsWith("get")) {
            getters.put(m.getName(), m);
        }
    }
}

From source file:org.evosuite.testcase.TestCodeVisitor.java

protected String getEnumValue(EnumPrimitiveStatement<?> statement) {
    Object value = statement.getValue();
    Class<?> clazz = statement.getEnumClass();
    String className = getClassName(clazz);

    try {//from w w w .  ja  v a2  s .  c om
        if (value.getClass().getField(value.toString()) != null)
            return className + "." + value;

    } catch (NoSuchFieldException e) {
        // Ignore
    }

    for (Field field : value.getClass().getDeclaredFields()) {
        if (field.isEnumConstant()) {
            try {
                if (field.get(value).equals(value)) {
                    return className + "." + field.getName();
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }
    return className + ".valueOf(\"" + value + "\")";

}

From source file:org.openhab.binding.weather.internal.metadata.MetadataHandler.java

/**
 * Scans the class and generates metadata.
 *///  w  w  w . jav a  2  s .c om
public void generate(Class<?> clazz) throws IllegalAccessException {
    if (clazz == null) {
        return;
    }

    for (Field field : clazz.getDeclaredFields()) {
        if (field.getType().getName().startsWith(PACKAGE_TO_SCAN) && !field.isEnumConstant()) {
            generate(field.getType());
        } else {
            for (Annotation annotation : field.getAnnotations()) {
                if (annotation.annotationType().equals(ProviderMappings.class)) {
                    ProviderMappings providerAnnotations = (ProviderMappings) annotation;
                    for (Provider provider : providerAnnotations.value()) {
                        Map<String, ProviderMappingInfo> mappings = providerMappings.get(provider.name());

                        if (mappings == null) {
                            mappings = new HashMap<String, ProviderMappingInfo>();
                            providerMappings.put(provider.name(), mappings);
                        }

                        Converter<?> converter = (Converter<?>) getConverter(field, provider.converter());
                        String target = clazz.getSimpleName().toLowerCase() + "." + field.getName();
                        ProviderMappingInfo pm = new ProviderMappingInfo(provider.property(), target,
                                converter);
                        mappings.put(pm.getSource(), pm);
                        logger.trace("Added provider mapping {}: {}", provider.name(), pm);
                    }
                } else if (annotation.annotationType().equals(ForecastMappings.class)) {
                    ForecastMappings forecastsAnnotations = (ForecastMappings) annotation;
                    for (Forecast forecast : forecastsAnnotations.value()) {
                        List<String> forecastProperties = forecastMappings.get(forecast.provider());
                        if (forecastProperties == null) {
                            forecastProperties = new ArrayList<String>();
                            forecastMappings.put(forecast.provider(), forecastProperties);
                        }
                        forecastProperties.add(forecast.property());
                        logger.trace("Added forecast mapping {}: {}", forecast.provider(), forecast.property());
                    }
                }
            }
        }
    }
}

From source file:org.openspotlight.common.util.Conversion.java

/**
 * Returns a new converted type based on target type parameter.
 * /*from w  w  w . j av  a  2s  .  c  o  m*/
 * @param <E>
 * @param rawValue
 * @param targetType
 * @return a new value from a converted type
 * @throws SLException
 */
@SuppressWarnings("unchecked")
public static <E> E convert(final Object rawValue, final Class<E> targetType) {
    Assertions.checkNotNull("targetType", targetType); //$NON-NLS-1$
    Assertions.checkCondition("validTargetType:" + targetType.getName(), //$NON-NLS-1$
            Conversion.CONVERTERS.containsKey(targetType) || targetType.isEnum());
    if (rawValue == null) {
        return null;
    }

    try {
        if (targetType.isEnum()) {
            final String rawValueAsString = rawValue.toString();
            final Field[] flds = targetType.getDeclaredFields();
            for (final Field f : flds) {
                if (f.isEnumConstant()) {
                    if (f.getName().equals(rawValueAsString)) {
                        final Object value = f.get(null);
                        return (E) value;

                    }
                }
            }
            throw new IllegalStateException(MessageFormat.format("Invalid enum constant:{0} for type {1}",
                    rawValueAsString, targetType));
        }
        final Converter converter = Conversion.CONVERTERS.get(targetType);
        final E converted = (E) converter.convert(targetType, rawValue);
        return converted;
    } catch (final Exception e) {
        throw Exceptions.logAndReturnNew(e, SLRuntimeException.class);
    }
}