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: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()));
        }//  w w  w  . j  av a  2s  .c o m
        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.shaf.core.util.ClassUtils.java

/**
 * Tests if the specified class represents an {@code Enum} type.
 * //from   w  ww  . j a  v  a  2 s . c  o  m
 * @param cls
 *            the class to test.
 * @return {@code true} if the class represents an {@code Enum} type and
 *         {@code false} otherwise.
 */
public static final boolean isEnum(final Class<?> cls) {
    if (cls == null) {
        throw new IllegalArgumentException("Undefined class.");
    }

    return cls.isEnum();
}

From source file:org.springframework.data.rest.webmvc.json.JsonSchema.java

/**
 * Turns the given {@link TypeInformation} into a JSON Schema type string.
 * /*from  w w w  . java  2s . c o m*/
 * @param typeInformation
 * @return
 * @see http://json-schema.org/latest/json-schema-core.html#anchor8
 */
private static String toJsonSchemaType(TypeInformation<?> typeInformation) {

    Class<?> type = typeInformation.getType();

    if (type == null) {
        return null;
    } else if (typeInformation.isCollectionLike()) {
        return "array";
    } else if (Boolean.class.equals(type) || boolean.class.equals(type)) {
        return "boolean";
    } else if (String.class.equals(type) || isDate(typeInformation) || type.isEnum()) {
        return "string";
    } else if (INTEGER_TYPES.contains(type)) {
        return "integer";
    } else if (ClassUtils.isAssignable(Number.class, type)) {
        return "number";
    } else {
        return "object";
    }
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static boolean isCollectionOrSequenceOrArrayOrEnum(Class<?> type) {
    if (!((ClassUtils.isAssignable(type, java.util.Collection.class)))
            || (ClassUtils.isAssignable(type, org.apache.pivot.collections.Collection.class))
            || (ClassUtils.isAssignable(type, org.apache.pivot.collections.Sequence.class))) {
        return type.isArray() || type.isEnum();
    }//from  w  w w .j  a  v  a2 s .c o  m

    return true;
}

From source file:demo.config.PropertyConverter.java

/**
 * Calls Class.isEnum() on Java 5, returns false on older JRE.
 *///from w  w w .  j a  v  a 2 s. c  om
static boolean isEnum(Class<?> cls) {
    return cls.isEnum();
}

From source file:net.servicefixture.converter.ObjectConverter.java

/**
 * Converts types that are supported by <code>ConvertUtils</code>.
 * // www  .  j a va2s  . co  m
 * @param data
 * @param destType
 * @return
 */
public static Object specialConvert(String data, Class destType) {
    try {
        //If it is enumeration class.
        if (ReflectionUtils.isEnumarationPatternClass(destType)) {
            try {
                Field field = destType.getField(data);
                return field.get(null);
            } catch (NoSuchFieldException e) {
                //No such field, meaning the variable name and the data
                //doesn't match, call fromString method.
                return destType.getMethod("fromString", new Class[] { String.class }).invoke(null,
                        new Object[] { data });
            }
        }
        //JDK5.0 enum type
        if (destType.isEnum()) {
            return destType.getMethod("valueOf", String.class).invoke(null, data);
        }
    } catch (Exception ignoreIt) {
        ignoreIt.printStackTrace();
    }

    throw new ServiceFixtureException("Unable to convert data:" + data + " to class:" + destType.getName());
}

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

/**
 * Coerce object type.//from  ww w. ja  v a2  s .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:utils.ReflectionService.java

public static Map createClassModel(Class clazz, int maxDeep) {
    Map map = new HashMap();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);/*from   ww  w.  j  a v a2s.c  o  m*/
        String key = field.getName();
        try {
            Class<?> type;
            if (Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                type = (Class<?>) collectionType.getActualTypeArguments()[0];
            } else {
                type = field.getType();
            }

            //            System.out.println(key + " ReflectionResource.createClassModel ==== putting type: " + field.getType().getName() + ", static: "
            //            + Modifier.isStatic(field.getModifiers()) + ", enum: " + type.isEnum() + ", java.*: " + type.getName().startsWith("java"));

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            } else if (type.isEnum()) {
                map.put(key, Enum.class.getName());
            } else if (!type.getName().startsWith("java") && !key.startsWith("_") && maxDeep > 0) {
                map.put(key, createClassModel(type, maxDeep - 1));
            } else {
                map.put(key, type.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return map;
}

From source file:com.bstek.dorado.data.entity.EntityUtils.java

/**
 * ???//from  w  ww . ja  v a  2 s . com
 */
public static boolean isSimpleType(Class<?> cl) {
    boolean b = (String.class.equals(cl) || cl.isPrimitive() || Boolean.class.equals(cl)
            || Number.class.isAssignableFrom(cl) || cl.isEnum() || Date.class.isAssignableFrom(cl)
            || Character.class.isAssignableFrom(cl));
    if (!b && cl.isArray()) {
        b = isSimpleType(cl.getComponentType());
    }
    return b;
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static Set<String> mapValueField(List<APIValueFieldModel> fieldModels, Field fields[],
        boolean onlyComsumeField) {
    Set<String> fieldNamesCaptured = new HashSet<>();

    for (Field field : fields) {
        boolean capture = true;

        if (onlyComsumeField) {
            ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
            if (consumeField == null) {
                capture = false;/*from w ww  .j  a v a  2  s  .  c om*/
            }
        }

        if (capture) {
            APIValueFieldModel fieldModel = new APIValueFieldModel();
            fieldModel.setFieldName(field.getName());
            fieldNamesCaptured.add(field.getName());
            fieldModel.setType(field.getType().getSimpleName());

            DataType dataType = (DataType) field.getAnnotation(DataType.class);
            if (dataType != null) {
                String typeName = dataType.value().getSimpleName();
                if (StringUtils.isNotBlank(dataType.actualClassName())) {
                    typeName = dataType.actualClassName();
                }
                fieldModel.setType(fieldModel.getType() + ":  " + typeName);
            }

            NotNull requiredParam = (NotNull) field.getAnnotation(NotNull.class);
            if (requiredParam != null) {
                fieldModel.setRequired(true);
            }

            StringBuilder validation = new StringBuilder();
            ParamTypeDescription description = (ParamTypeDescription) field
                    .getAnnotation(ParamTypeDescription.class);
            if (description != null) {
                validation.append(description.value()).append("<br>");
            }

            APIDescription aPIDescription = (APIDescription) field.getAnnotation(APIDescription.class);
            if (aPIDescription != null) {
                fieldModel.setDescription(aPIDescription.value());
            }

            if ("Date".equals(field.getType().getSimpleName())) {
                validation.append("Timestamp (milliseconds since UNIX Epoch<br>");
            }

            if ("boolean".equalsIgnoreCase(field.getType().getSimpleName())) {
                validation.append("T | F");
            }

            ValidationRequirement validationRequirement = (ValidationRequirement) field
                    .getAnnotation(ValidationRequirement.class);
            if (validationRequirement != null) {
                validation.append(validationRequirement.value()).append("<br>");
            }

            PK pk = (PK) field.getAnnotation(PK.class);
            if (pk != null) {
                if (pk.generated()) {
                    validation.append("Primary Key (Generated)").append("<br>");
                } else {
                    validation.append("Primary Key").append("<br>");
                }
            }

            Min min = (Min) field.getAnnotation(Min.class);
            if (min != null) {
                validation.append("Min Value: ").append(min.value()).append("<br>");
            }

            Max max = (Max) field.getAnnotation(Max.class);
            if (max != null) {
                validation.append("Max Value: ").append(max.value()).append("<br>");
            }

            Size size = (Size) field.getAnnotation(Size.class);
            if (size != null) {
                validation.append("Min Length: ").append(size.min()).append(" Max Length: ").append(size.max())
                        .append("<br>");
            }

            Pattern pattern = (Pattern) field.getAnnotation(Pattern.class);
            if (pattern != null) {
                validation.append("Needs to Match: ").append(pattern.regexp()).append("<br>");
            }

            ValidValueType validValueType = (ValidValueType) field.getAnnotation(ValidValueType.class);
            if (validValueType != null) {
                validation.append("Set of valid values: ").append(Arrays.toString(validValueType.value()))
                        .append("<br>");
                if (validValueType.lookupClass().length > 0) {
                    validation.append("See Lookup table(s): <br>");
                    for (Class lookupClass : validValueType.lookupClass()) {
                        validation.append(lookupClass.getSimpleName());
                    }
                }
                if (validValueType.enumClass().length > 0) {
                    validation.append("See Enum List: <br>");
                    for (Class enumClass : validValueType.enumClass()) {
                        validation.append(enumClass.getSimpleName());
                        if (enumClass.isEnum()) {
                            validation.append(" (").append(Arrays.toString(enumClass.getEnumConstants()))
                                    .append(") ");
                        }
                    }
                }
            }

            fieldModel.setValidation(validation.toString());

            fieldModels.add(fieldModel);
        }
    }
    return fieldNamesCaptured;
}