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.megatome.frame2.introspector.Converter.java

static Object convertValueToType(Object value, Class<?> type) throws Exception {
    if ((value == null) || (type == null)) {
        return null;
    }/*from   w w  w .  j a  v a2s  .  co m*/

    if (value.getClass() == type) {
        return value;
    }

    if (value instanceof FileItem) {
        return value;
    }

    String strValue = null;

    if (value instanceof String) {
        strValue = (String) value;
    } else {
        strValue = String.valueOf(value);
        LOGGER.warn("Trying to convert from a non String type. Results may be varied."); //$NON-NLS-1$
    }

    TypeConverter converter = converterMap.get(type);
    if (type.isEnum()) {
        converter = new EnumConverter();
    }

    if (converter != null) {
        if (type.isEnum()) {
            ((EnumConverter) converter).setType(type);
        }
        return converter.convert(strValue);
    }

    return null;
}

From source file:com.addthis.codec.config.Configs.java

private static boolean isCodableType(CodableFieldInfo fieldInfo) {
    Class<?> expectedType = elementType(fieldInfo);
    if (expectedType.isAssignableFrom(String.class)) {
        return false;
    } else if ((expectedType == boolean.class) || (expectedType == Boolean.class)) {
        return false;
    } else if (expectedType == AtomicBoolean.class) {
        return false;
    } else if (Number.class.isAssignableFrom(expectedType) || expectedType.isPrimitive()) {
        // primitive numeric types are not subclasses of Number, so just catch all non-booleans
        return false;
    } else if (expectedType.isEnum()) {
        return false;
    } else {//from w w w  .j a  v a 2 s.  co  m
        return true;
    }
}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleObjectType(Class<?> classz, StringBuilder sb,
        JsonSchemaProperty propertyDescriptor, Map<String, String> declarations, boolean topLevel,
        String uriPrefix) {// ww  w. ja  va2 s  .  com
    boolean result = false;
    String prepend = "";
    Map<String, Boolean> flags = new HashMap<String, Boolean>();
    flags.put("hasTitle", false);
    flags.put("hasDescription", false);
    flags.put("hasType", false);
    flags.put("hasEnum", false);

    if (classz.isEnum()) {
        sb.append("\"type\":\"string\",");
        sb.append("\"enum\":[");
        for (Enum<?> c : (Enum<?>[]) classz.getEnumConstants()) {
            sb.append("\"");
            sb.append(c.toString());
            sb.append("\", ");
        }
        sb.append("]");
        flags.put("hasType", true);
        flags.put("hasEnum", true);
        result = true;
    }
    if (!flags.get("hasType")) {
        sb.append(prepend);
        sb.append("\"type\":\"object\"");
        prepend = ", ";
        flags.put("hasType", true);
        result = true;
    }
    if (handlePropertyDescriptor(sb, propertyDescriptor, flags, prepend, result, uriPrefix)) {
        result = true;
    }
    JsonSchemaClass annotation = classz.getAnnotation(JsonSchemaClass.class);
    if (annotation != null) {
        if (result == true)
            prepend = ", ";

        if (!StringUtils.isEmpty(annotation.id())) {
            sb.append(prepend);
            sb.append("\"id\":\"" + annotation.id() + "\"");
            prepend = ", ";
        }
        if (!flags.get("hasTitle") && !StringUtils.isEmpty(annotation.title())) {
            sb.append(prepend);
            sb.append("\"title\":\"" + annotation.title() + "\"");
            prepend = ", ";
        }
        if (!flags.get("hasDescription") && !StringUtils.isEmpty(annotation.description())) {
            sb.append(prepend);
            sb.append("\"description\":\"" + annotation.description() + "\"");
            prepend = ", ";
        }
        result = true;
    }

    sb.append(prepend);
    sb.append("\"properties\":");
    handleProperties(classz, sb, declarations, uriPrefix);
    prepend = ", ";
    return result;
}

From source file:org.waveprotocol.box.server.util.ClientFlagsUtil.java

/**
 * Checks parameter for validity.//from w  w w  .java 2  s . com
 * 
 * @param name parameter name in CamelCase format
 * @param value parameter value
 * @throws IllegalArgumentException if the parameter is invalid
 */
public static void checkParameter(String name, String value) throws IllegalArgumentException {
    String shortName = FlagConstants.getShortName(name);
    if (shortName == null) {
        throw new IllegalArgumentException(String.format("Unknown parameter: %s!", name));
    }

    Method getter;
    try {
        getter = ClientFlags.class.getMethod(name);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(String.format("Unknown method %s() in ClientFlags class!", name));
    }

    Class<?> retType = getter.getReturnType();
    boolean correct = true;
    if (retType.equals(String.class)) {
        correct = ValueUtils.isEmbracedWith(value, "\"");
    } else if (retType.equals(int.class)) {
        try {
            Integer.parseInt(value);
        } catch (NumberFormatException e) {
            correct = false;
        }
    } else if (retType.equals(boolean.class)) {
        correct = value.equals("true") || value.equals("false");
    } else if (retType.equals(double.class)) {
        try {
            Double.parseDouble(value);
        } catch (NumberFormatException e) {
            correct = false;
        }
    } else if (retType.isEnum()) {
        // check enum
        String enumValues = ValueUtils.stripFrom(Arrays.toString(retType.getEnumConstants()), "[", "]");
        correct = false;
        String upperValue = value.toUpperCase();
        for (String enumValue : enumValues.split(",")) {
            if (upperValue.equals(enumValue.trim())) {
                correct = true;
                break;
            }
        }
    } else {
        throw new IllegalArgumentException(
                String.format("Unknown parameter type (%s) for parameter %s", retType, name));
    }

    if (!correct) {
        throw new IllegalArgumentException(
                String.format("Invalid parameter: name=%s, type=%s, value=%s", name, retType, value));
    }
}

From source file:org.jboss.dashboard.commons.misc.ReflectionUtils.java

public static List<Field> getClassFields(Class clazz, Class type, boolean isStatic, String[] fieldsToIgnore) {
    List<Field> results = new ArrayList<Field>();
    if (clazz == null)
        return results;
    if (clazz.isPrimitive())
        return results;
    if (clazz.isAnnotation())
        return results;
    if (clazz.isInterface())
        return results;
    if (clazz.isEnum())
        return results;

    Collection<String> toIgnore = fieldsToIgnore != null ? Arrays.asList(fieldsToIgnore)
            : Collections.EMPTY_SET;
    Field[] fields = clazz.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];//from   w ww  . j ava 2s .  co  m
        if (toIgnore.contains(field.getName()))
            continue;
        if (isStatic && !Modifier.isStatic(field.getModifiers()))
            continue;
        if (!isStatic && Modifier.isStatic(field.getModifiers()))
            continue;
        if (type != null && !field.getType().equals(type))
            continue;
        results.add(field);
    }
    return results;
}

From source file:org.xmlsh.util.JavaUtils.java

public static boolean isAtomicClass(Class<?> cls) {
    return cls.isEnum() || isWrappedOrPrimativeNumber(cls) || isStringClass(cls);

}

From source file:Main.java

/**
 * convert value to given type./*from w ww .j a v a  2 s.  co  m*/
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:org.lman.json.JsonConverter.java

private static Object readJson(Object json, Class<?> clazz, TypeParameter typeParameter)
        throws ReadJsonException, InstantiationException, IllegalAccessException, JSONException,
        IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
    if (json == null || json == JSONObject.NULL) {
        return null;
    } else if (clazz == String.class || clazz == Boolean.class || clazz == Integer.class) {
        return json;
    } else if (clazz == Long.class) {
        // It's a Number but not an Integer, need to convert it into an integer for JSON :(
        return Long.valueOf(((Number) json).longValue());
    } else if (Collection.class.isAssignableFrom(clazz)) {
        return readCollection(json, clazz, typeParameter);
    } else if (clazz.isEnum()) {
        return readEnum(json, clazz);
    } else if (Map.class.isAssignableFrom(clazz)) {
        if (typeParameter == null)
            throw new ReadJsonException("Missing type parameter");
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject jsonObject = (JSONObject) json;
        for (String key : jsonObject.keySet())
            map.put(key, readJson(jsonObject.get(key), typeParameter.value(), null));
        return map;
    } else {//from  w  w w .java2  s . c  o  m
        if (!(json instanceof JSONObject))
            throw new ReadJsonException(
                    json + " not a JSONObject (is " + json.getClass() + " for clazz " + clazz + ")");
        Object object = clazz.newInstance();
        for (Field field : clazz.getFields()) {
            if (Modifier.isStatic(field.getModifiers()))
                continue;

            try {
                Object readObject = readJson(((JSONObject) json).get(field.getName()), field.getType(),
                        field.getAnnotation(TypeParameter.class));
                field.set(object, readObject);
            } catch (JSONException e) {
                // Ok, probably just not found.
            }
        }
        return object;
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

private static boolean isByRef(Class<?> param, Annotation[] annotations) {
    // if parameter has ByValue annotation, it is ByValueParameter
    if (containsAnnotation(annotations, ByValueParameter.class))
        return false;

    // if this is primitive or wrapper type, it is ByValueParameter
    if (param.isPrimitive() || param.equals(String.class) || Primitives.allWrapperTypes().contains(param))
        return false;

    // if this is enum, it is ByValueParameter
    if (param.isEnum())
        return false;

    // if parameter class has ByValueParameter annotation, it is ByValueParameter
    if (param.isAnnotationPresent(ByValueParameter.class))
        return false;

    // otherwise it is ByRefParameter
    return true;/*from w w  w.  j  a va2s .co m*/
}

From source file:edu.usu.sdl.openstorefront.validation.ValidationUtil.java

private static List<RuleResult> validateFields(final ValidationModel validateModel, Class dataClass,
        String parentFieldName, String parentType) {
    List<RuleResult> ruleResults = new ArrayList<>();

    if (validateModel.getDataObject() == null && validateModel.isAcceptNull() == false) {
        RuleResult validationResult = new RuleResult();
        validationResult.setMessage("The whole data object is null.");
        validationResult.setValidationRule("Don't allow null object");
        validationResult.setEntityClassName(parentType);
        validationResult.setFieldName(parentFieldName);
        ruleResults.add(validationResult);
    } else {//from  w ww  . j av  a  2  s  .  c  o m
        if (validateModel.getDataObject() != null) {
            if (dataClass.getSuperclass() != null) {
                ruleResults.addAll(validateFields(validateModel, dataClass.getSuperclass(), null, null));
            }

            for (Field field : dataClass.getDeclaredFields()) {
                Class fieldClass = field.getType();
                boolean process = true;
                if (validateModel.isConsumeFieldsOnly()) {
                    ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
                    if (consumeField == null) {
                        process = false;
                    }
                }

                if (process) {
                    if (ReflectionUtil.isComplexClass(fieldClass)) {
                        //composition class
                        if (Logger.class.getName().equals(fieldClass.getName()) == false
                                && fieldClass.isEnum() == false) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                boolean check = true;
                                if (returnObj == null) {
                                    NotNull notNull = (NotNull) fieldClass.getAnnotation(NotNull.class);
                                    if (notNull == null) {
                                        check = false;
                                    }
                                }
                                if (check) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, returnObj),
                                                    fieldClass, field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(List.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Collection.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Set.class.getSimpleName())) {
                        //multi
                        if (fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                Map mapObj = (Map) returnObj;
                                for (Object entryObj : mapObj.entrySet()) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, entryObj),
                                                    entryObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        } else {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                if (returnObj != null) {
                                    for (Object itemObj : (Collection) returnObj) {
                                        if (itemObj != null) {
                                            ruleResults.addAll(validateFields(
                                                    ValidationModel.copy(validateModel, itemObj),
                                                    itemObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                        } else {
                                            log.log(Level.WARNING,
                                                    "There is a NULL item in a collection.  Check data passed in to validation.");
                                        }
                                    }
                                } else {
                                    NotNull notNull = field.getAnnotation(NotNull.class);
                                    if (notNull != null) {
                                        RuleResult ruleResult = new RuleResult();
                                        ruleResult.setMessage("Collection is required");
                                        ruleResult.setEntityClassName(
                                                validateModel.getDataObject().getClass().getSimpleName());
                                        ruleResult.setFieldName(field.getName());
                                        ruleResult.setValidationRule("Requires value");
                                        ruleResults.add(ruleResult);
                                    }
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }

                    } else {
                        //simple case
                        for (BaseRule rule : rules) {
                            //Stanize if requested
                            if (validateModel.getSantize()) {
                                Sanitize santize = field.getAnnotation(Sanitize.class);
                                if (santize != null) {
                                    try {
                                        Sanitizer santizer = santize.value().newInstance();

                                        Method method = dataClass.getMethod(
                                                "get" + StringUtils.capitalize(field.getName()),
                                                (Class<?>[]) null);
                                        Object returnObj = method.invoke(validateModel.getDataObject(),
                                                (Object[]) null);

                                        Object newValue = santizer.santize(returnObj);

                                        method = dataClass.getMethod(
                                                "set" + StringUtils.capitalize(field.getName()), String.class);
                                        method.invoke(validateModel.getDataObject(), newValue);

                                    } catch (InstantiationException | IllegalAccessException
                                            | NoSuchMethodException | SecurityException
                                            | InvocationTargetException ex) {
                                        throw new OpenStorefrontRuntimeException(ex);
                                    }
                                }
                            }

                            RuleResult validationResult = rule.processField(field,
                                    validateModel.getDataObject());
                            if (validationResult != null) {
                                ruleResults.add(validationResult);
                            }
                        }
                    }
                }
            }
        }
    }

    return ruleResults;
}