Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

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

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override//  w  ww .  j  av  a2s .  c om
public <T> String convertToString(final Class<T> type, final T instance, final Locale locale,
        final String format) throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    String result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug(
                "Converting to string with type {} with locale {}, format {} and value: {}", type, locale,
                format, instance);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        final Enum<?> enumInstance = enumType.cast(instance);
        if (!CheckUtil.isNull(enumInstance)) {
            result = enumInstance.name();
        }
    } else {
        result = this.converterTool.convertToString(type, instance, locale, format);
    }
    return result;
}

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override//ww  w.  j  a  va2 s  .  c  o  m
public <T> T convertToInstance(final Class<T> type, final String stringValue, final Locale locale,
        final String format) throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    T result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug(
                "Converting to instance type {} with locale {}, format {} and value: {}", type, locale, format,
                stringValue);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        if (!StringUtil.isEmptyString(stringValue)) {
            result = (T) Enum.valueOf(enumType, stringValue);
        }
    } else {
        result = this.converterTool.convertToInstance(type, stringValue, locale, format);
    }
    return result;
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

public Object convertStringToObject(String value, Class type) {
    if (type.isEnum()) {
        return Enum.valueOf(type, value);
    } else if (String.class.equals(type)) {
        return value;
    }/*from   w  w  w  .  ja  v a2s  .  com*/

    if (StringUtils.isBlank(value)) {
        return null;
    } else if (Number.class.equals(type)) {
        return NumberUtils.createNumber(value);
    } else if (Integer.class.equals(type) || Integer.TYPE.equals(type)) {
        return new Integer(value);
    } else if (Long.class.equals(type) || Long.TYPE.equals(type)) {
        return Long.valueOf(value);
    } else if (Double.class.equals(type) || Double.TYPE.equals(type)) {
        return Double.valueOf(value);
    } else if (Float.class.equals(type) || Float.TYPE.equals(type)) {
        return Float.valueOf(value);
    } else if (Pattern.class.equals(type)) {
        return Pattern.compile(value);
    } else if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) {
        return BooleanUtils.toBoolean(value);
    } else {
        throw new IllegalArgumentException(
                "Unable to convert the value " + value + " to an object of type " + type.getName());
    }

}

From source file:org.vulpe.view.tags.Functions.java

/**
 *
 * @param bean//  w w  w .  ja  va  2 s  . co  m
 * @param field
 * @param fieldValue
 * @return
 * @throws JspException
 */
public static Object enumInField(final Object bean, final String field, final Object fieldValue)
        throws JspException {
    try {
        if (bean == null) {
            return null;
        }
        final String[] fieldParts = field.replace(".id", "").split("\\.");
        Class<?> fieldClass = null;
        if (fieldParts.length == 1) {
            fieldClass = VulpeReflectUtil.getFieldClass(bean.getClass(), fieldParts[0]);
        } else {
            int count = 1;
            Class<?> parentClass = bean.getClass();
            for (final String fieldPart : fieldParts) {
                parentClass = VulpeReflectUtil.getFieldClass(parentClass, fieldPart);
                ++count;
                if (count == fieldParts.length) {
                    fieldClass = VulpeReflectUtil.getFieldClass(parentClass, fieldParts[fieldParts.length - 1]);
                }
            }
        }
        if (fieldClass == null) {
            return null;
        }
        if (fieldClass.isEnum()) {
            for (final Object item : fieldClass.getEnumConstants()) {
                if (item.equals(fieldValue) || item.toString().equals(fieldValue)) {
                    return findText(fieldClass.getName().concat(".").concat(item.toString()));
                }
            }
        }
        return null;
    } catch (Exception e) {
        throw new JspException(e);
    }
}

From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java

protected Variable doBuildVariable(Class<?> propertyType, String name) {
    ValueType type = ValueType.Factory.forClass(propertyType);

    Variable.Builder builder = Variable.Builder.newVariable(name, type, entityType);
    if (propertyType.isEnum()) {
        Enum<?>[] constants = (Enum<?>[]) propertyType.getEnumConstants();
        String[] names = Iterables.toArray(
                Iterables.transform(Arrays.asList(constants), Functions.toStringFunction()), String.class);
        builder.addCategories(names);// w ww  .  j ava 2 s.  c o  m
    }

    if (occurrenceGroup != null) {
        builder.repeatable().occurrenceGroup(occurrenceGroup);
    }

    builder.accept(variableBuilderVisitors);

    // Allow extended classes to contribute to the builder
    return buildVariable(builder).build();
}

From source file:com.facebook.stetho.json.ObjectMapper.java

private List<Object> convertArrayToList(Field field, JSONArray array)
        throws IllegalAccessException, JSONException {
    if (List.class.isAssignableFrom(field.getType())) {
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        Type[] types = parameterizedType.getActualTypeArguments();
        if (types.length != 1) {
            throw new IllegalArgumentException(
                    "Only able to handle a single type in a list " + field.getName());
        }//  ww  w .  j  a  v  a2 s .c om
        Class arrayClass = (Class) types[0];
        List<Object> objectList = new ArrayList<Object>();
        for (int i = 0; i < array.length(); ++i) {
            if (arrayClass.isEnum()) {
                objectList.add(getEnumValue(array.getString(i), arrayClass));
            } else if (canDirectlySerializeClass(arrayClass)) {
                objectList.add(array.get(i));
            } else {
                JSONObject jsonObject = array.getJSONObject(i);
                if (jsonObject == null) {
                    objectList.add(null);
                } else {
                    objectList.add(convertValue(jsonObject, arrayClass));
                }
            }
        }
        return objectList;
    } else {
        throw new IllegalArgumentException("only know how to deserialize List<?> on field " + field.getName());
    }
}

From source file:org.jtester.hamcrest.matcher.property.report.ObjectFormatter.java

/**
 * Actual implementation of the formatting.
 * //  w  w w . j  av a  2s  .  c  o  m
 * @param object
 *            The instance
 * @param currentDepth
 *            The current recursion depth
 * @param result
 *            The builder to append the result to, not null
 */
protected void formatImpl(Object object, int currentDepth, StringBuilder result) {
    // get the actual value if the value is wrapped by a Hibernate proxy
    object = getUnproxiedValue(object);

    if (object == null) {
        result.append(String.valueOf(object));
        return;
    }
    if (object instanceof String) {
        result.append('"');
        result.append(object);
        result.append('"');
        return;
    }
    if (object instanceof Number || object instanceof Date) {
        result.append(String.valueOf(object));
        return;
    }
    if (object instanceof Character) {
        result.append('\'');
        result.append(String.valueOf(object));
        result.append('\'');
        return;
    }
    Class dummyObjectClass = getDummyObjectClass();
    if (dummyObjectClass != null && dummyObjectClass.isAssignableFrom(object.getClass())) {
        result.append("Dummy<");
        result.append(object.toString());
        result.append(">");
        return;
    }
    Class type = object.getClass();
    if (type.isPrimitive() || type.isEnum()) {
        result.append(String.valueOf(object));
        return;
    }
    if (formatMock(object, result)) {
        return;
    }
    if (formatProxy(object, result)) {
        return;
    }
    if (type.getName().startsWith("java.lang")) {
        result.append(String.valueOf(object));
        return;
    }
    if (type.isArray()) {
        formatArray(object, currentDepth, result);
        return;
    }
    if (object instanceof Collection) {
        formatCollection((Collection<?>) object, currentDepth, result);
        return;
    }
    if (object instanceof Map) {
        formatMap((Map<?, ?>) object, currentDepth, result);
        return;
    }
    if (currentDepth >= maxDepth) {
        result.append(getShortClassName(type));
        result.append("<...>");
        return;
    }
    formatObject(object, currentDepth, result);
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanFactory.java

public void init() throws Exception {
    if (this.__beanLoader == null) {
        if (this.__parentFactory != null) {
            this.__beanLoader = this.__parentFactory.getLoader();
        }//from   www.j  av  a2  s  .  c o  m
        if (this.__beanLoader == null) {
            this.__beanLoader = new DefaultBeanLoader();
        }
    }
    if (!__packageNames.isEmpty())
        for (String _packageName : __packageNames) {
            List<Class<?>> _classes = this.__beanLoader.load(_packageName);
            for (Class<?> _class : _classes) {
                // ?????
                if (!_class.isAnnotation() && !_class.isEnum() && !_class.isInterface()) {
                    Annotation[] _annotations = _class.getAnnotations();
                    if (_annotations != null && _annotations.length > 0) {
                        for (Annotation _anno : _annotations) {
                            IBeanHandler _handler = __beanHandlerMap.get(_anno.annotationType());
                            if (_handler != null) {
                                Object _instance = _handler.handle(_class);
                                if (_instance != null) {
                                    if (_instance instanceof BeanMeta) {
                                        __addClass((BeanMeta) _instance);
                                    } else {
                                        __addClass(BeanMeta.create(_instance, _class));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
}

From source file:com.thinkbiganalytics.metadata.modeshape.common.JcrObject.java

public <T> T getPropertyFromNode(Node node, String name, Class<T> type, boolean allowNotFound) {
    Object o = JcrPropertyUtil.getProperty(node, name, allowNotFound);
    if (allowNotFound && o == null) {
        return null;
    }/*from   w w w  . ja v a  2 s  . c  o m*/
    if (type.isEnum()) {
        String savedType = o.toString();
        if (StringUtils.isNotBlank(savedType)) {
            Class<? extends Enum> x = (Class<? extends Enum>) type;
            return (T) Enum.valueOf(x, savedType);
        }
    }
    if (!o.getClass().isAssignableFrom(type)) {
        //if it cant be matched and it is a Node > JcrObject, do the conversion
        if (o instanceof Node && JcrObject.class.isAssignableFrom(type)) {
            return JcrUtil.constructNodeObject((Node) o, type, null);
        } else {
            throw new MetadataRepositoryException("Unable to convert Property " + name + " to type " + type);
        }
    } else {
        return (T) o;
    }
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumAtRootCreatesATopLevelType() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumAsRoot.json",
            "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.EnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));

}