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:utils.ReflectionService.java

public static JsonNode createJsonNode(Class clazz, int maxDeep) {

    if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) {
        return null;
    }//from  ww  w  . j  a v a  2 s. com

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode objectNode = objectMapper.createObjectNode();

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {
            // is array or collection
            if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0];
                ArrayNode arrayNode = objectMapper.createArrayNode();
                arrayNode.add(createJsonNode(type, maxDeep - 1));
                objectNode.put(key, arrayNode);
            } else {
                Class<?> type = field.getType();
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                } else if (type.isEnum()) {
                    objectNode.put(key, Enum.class.getName());
                } else if (!type.getName().startsWith("java") && !key.startsWith("_")) {
                    objectNode.put(key, createJsonNode(type, maxDeep - 1));
                } else {
                    objectNode.put(key, type.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return objectNode;
}

From source file:org.openhab.io.neeo.internal.NeeoUtil.java

/**
 * Gets the {@link Command} for the specified enum name - ignoring case
 *
 * @param cmd      the non-null {@link Command}
 * @param enumName the non-empty enum name to search for
 * @return the {@link Command} or null if not found (or null if cmd's class is not an enum)
 *//*from  w  w  w . j  av  a 2 s .c  o  m*/
@Nullable
static Command getEnum(Class<? extends Command> cmd, String enumName) {
    Objects.requireNonNull(cmd, "cmd cannot be null");
    requireNotEmpty(enumName, "enumName cannot be null");

    if (cmd.isEnum()) {
        for (Command cmdEnum : cmd.getEnumConstants()) {
            if (StringUtils.equalsIgnoreCase(((Enum<?>) cmdEnum).name(), enumName)) {
                return cmdEnum;
            }
        }
    }
    return null;
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

private static boolean assignPropertyValue(PropertyDescriptor sourceProp, Object sourceValue,
        PropertyDescriptor destProp, Object destInstance) {
    if (sourceValue == null) {
        System.out.println("Null value found, assignment skipped");
        return true;
    }//from  ww w  .j a v  a  2  s .  c  o  m
    boolean result = false;
    Class<?> sourceType = sourceProp.getPropertyType();
    Method getter = sourceProp.getReadMethod();
    Class<?> destType = destProp.getPropertyType();
    Method setter = destProp.getWriteMethod();
    try {
        if (destType.isInterface() || destType.isArray() || destType.isEnum()) {
            if (Collection.class.isAssignableFrom(sourceType) && Collection.class.isAssignableFrom(destType))
                assignCollectionValue(getter, sourceValue, destType, setter, destInstance);
            else if (Map.class.isAssignableFrom(sourceType) && Map.class.isAssignableFrom(destType))
                assignMapValue(getter, sourceValue, setter, destInstance);
            else
                assignMixedTypesValue(sourceType, getter, sourceValue, destType, setter, destInstance);
        } else if (destType.isInstance(sourceValue) || destType.isPrimitive())
            setter.invoke(destInstance, sourceValue);

        else if (destType.isMemberClass())
            setter.invoke(destInstance, sourceValue);

        else if (destType.isAssignableFrom(sourceType))
            setter.invoke(destInstance, destType.cast(sourceValue));

        else { //if (ClassUtils.isInnerClass(destType)) {
            Object member = transposeModel(sourceType, destType, sourceValue);
            member = destType.cast(member);
            setter.invoke(destInstance, member);
        }
        result = true;
    } catch (IllegalArgumentException ex) {
        System.out.println("Looks like type mismatch, source type: " + sourceType + ", dest type: " + destType);
        Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException | IllegalAccessException ex) {
        Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static void changeObject(Map<String, Object> map, String key, Object value, Class clazz,
        String dataFormat) throws ParseException {
    if (value instanceof String) {
        String valueStr = (String) value;
        if (clazz.isEnum()) {
            map.put(key, Enum.valueOf(clazz, valueStr));
        } else if (clazz == Date.class) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_DATE_PATTERN);
            Date date = sdf.parse(valueStr);
            map.put(key, date);/*from  w w  w.  ja v  a2  s.co  m*/
        } else if (clazz == Integer.class) {
            map.put(key, Integer.valueOf(valueStr));
        } else if (clazz == BigDecimal.class) {
            map.put(key, new BigDecimal(valueStr));
        } else if (clazz == Boolean.class) {
            map.put(key, new Boolean(valueStr));
        } else if (clazz == Number.class) {
            map.put(key, new Integer(valueStr));
        } else if (clazz == int.class) {
            map.put(key, Integer.parseInt(valueStr));
        } else {
            map.put(key, valueStr);
        }
    } else if (value instanceof Integer) {
        Integer valueInt = (Integer) value;
        if (clazz == String.class) {
            map.put(key, valueInt.toString());
        } else if (clazz == Date.class) {
            map.put(key, new Date(valueInt));
        } else {
            map.put(key, valueInt);
        }
    } else if (value instanceof Boolean) {
        Boolean valueBoolean = (Boolean) value;
        if (clazz == String.class) {
            map.put(key, valueBoolean.toString());
        } else {
            map.put(key, valueBoolean);
        }
    } else if (value instanceof Date) {
        Date valueDate = (Date) value;
        if (clazz == String.class) {
            SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
            map.put(key, sdf.format(valueDate));
        } else {
            map.put(key, valueDate);
        }
    } else if (value instanceof BigDecimal) {
        BigDecimal valueBigDecimal = (BigDecimal) value;
        if (clazz == String.class) {
            map.put(key, valueBigDecimal.toPlainString());
        } else if (clazz == Integer.class) {
            map.put(key, valueBigDecimal.toBigInteger());
        } else {
            map.put(key, valueBigDecimal);
        }
    } else {
        map.put(key, value);
    }
}

From source file:password.pwm.util.java.JavaHelper.java

public static <E extends Enum<E>> E readEnumFromString(final Class<E> enumClass, final E defaultValue,
        final String input) {
    if (StringUtil.isEmpty(input)) {
        return defaultValue;
    }/*from w  w w. j a  v a2  s  .  c  o m*/

    if (enumClass == null || !enumClass.isEnum()) {
        return defaultValue;
    }

    try {
        return Enum.valueOf(enumClass, input);
    } catch (IllegalArgumentException e) {
        /* noop */
        //LOGGER.trace("input=" + input + " does not exist in enumClass=" + enumClass.getSimpleName());
    } catch (Throwable e) {
        LOGGER.warn("unexpected error translating input=" + input + " to enumClass=" + enumClass.getSimpleName()
                + ", error: " + e.getMessage());
    }

    return defaultValue;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

private static boolean checkMatch(Class<?> parameterType, Object arg) {
    // skip enum if argument was String. We will try valueOf() later
    if (!(arg instanceof String && parameterType.isEnum())
            && !ClassUtils.isAssignable(arg == null ? null : arg.getClass(), parameterType, true)) {
        return false;
    }/*from  w  w w  . j  av  a  2s.  c om*/
    return true;
}

From source file:io.konik.utils.RandomInvoiceGenerator.java

private static boolean isLeafType(Class<?> type) {
    if (type.equals(Class.class))
        return true;
    if (isAssignable(ZfDate.class, type))
        return true;
    if (isAssignable(Date.class, type))
        return true;
    if (isAssignable(String.class, type))
        return true;
    if (BigDecimal.class.isAssignableFrom(type))
        return true;
    if (type.isEnum())
        return true;
    if (type.equals(Profile.class))
        return true;
    return isPrimitiveOrWrapper(type);
}

From source file:com.bloatit.framework.webprocessor.url.Loaders.java

private @SuppressWarnings({ "unchecked", "synthetic-access", "rawtypes" }) static <T> Loader<T> getLoader(
        final Class<T> theClass) {
    if (theClass.equals(Integer.class)) {
        return (Loader<T>) new ToInteger();
    }/*from   w  w w . j  a  v  a 2s . com*/
    if (theClass.equals(Byte.class)) {
        return (Loader<T>) new ToByte();
    }
    if (theClass.isEnum()) {
        return new ToEnum(theClass);
    }
    if (theClass.equals(Short.class)) {
        return (Loader<T>) new ToShort();
    }
    if (theClass.equals(Long.class)) {
        return (Loader<T>) new ToLong();
    }
    if (theClass.equals(Float.class)) {
        return (Loader<T>) new ToFloat();
    }
    if (theClass.equals(Double.class)) {
        return (Loader<T>) new ToDouble();
    }
    if (theClass.equals(Character.class)) {
        return (Loader<T>) new ToCharacter();
    }
    if (theClass.equals(Boolean.class)) {
        return (Loader<T>) new ToBoolean();
    }
    if (theClass.equals(BigDecimal.class)) {
        return (Loader<T>) new ToBigdecimal();
    }
    if (theClass.equals(String.class)) {
        return (Loader<T>) new ToString();
    }
    if (theClass.equals(Locale.class)) {
        return (Loader<T>) new ToLocale();
    }
    if (theClass.equals(Date.class)) {
        return (Loader<T>) new ToDate();
    }
    if (Commentable.class.equals(theClass)) {
        return (Loader<T>) new ToCommentable();
    }
    if (theClass.equals(DateLocale.class)) {
        return (Loader<T>) new ToBloatitDate();
    }
    if (IdentifiableInterface.class.isAssignableFrom(theClass)) {
        return new ToIdentifiable(theClass);
    }
    if (WebProcess.class.isAssignableFrom(theClass)) {
        return new ToWebProcess();
    }
    throw new NotImplementedException("Cannot find a conversion class for: " + theClass);
}

From source file:com.smartbear.postman.PostmanImporter.java

private static String createProjectName(String collectionName, List<? extends Project> projectList) {
    Class clazz;
    try {// w  w  w.  j  av  a  2  s  .co m
        clazz = Class.forName("com.eviware.soapui.support.ModelItemNamer$NumberSuffixStrategy");
        Method method = ModelItemNamer.class.getMethod("createName", String.class, Iterable.class, clazz);
        if (clazz.isEnum()) {
            return (String) method.invoke(null, collectionName, projectList,
                    Enum.valueOf(clazz, "SUFFIX_WHEN_CONFLICT_FOUND"));
        }
    } catch (Throwable e) {
        logger.warn("Setting number suffix strategy is only supported in Ready! API", e);
    }

    return ModelItemNamer.createName(collectionName, projectList);
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * TODO: provide support for nested JSON objects
 * TODO: provide support for embedded JSON Arrays
 *
 * @param jsonObject// w  w  w. ja  v a  2  s .c  om
 * @param beanToBeCreatedClass
 * @param <T>
 * @return
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws JSONException
 * @throws NoSuchMethodException
 * @throws java.lang.reflect.InvocationTargetException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass)
        throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException,
        InvocationTargetException {
    T value = beanToBeCreatedClass.getConstructor().newInstance();

    Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object field = jsonObject.get(key);

        //  capitalise to standard setter pattern
        String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1);

        //System.err.println("method name:" + methodName);

        Method method = getCandidateMethod(beanToBeCreatedClass, methodName);

        if (method != null) {
            Class clazz = method.getParameterTypes()[0];

            // discriminate based on type
            if (field.equals(JSONObject.NULL)) {
                method.invoke(value, clazz.cast(null));
            } else if (field instanceof String) {
                // check if we're an enum
                if (clazz.isEnum()) {
                    Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field);
                    try {
                        beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm);
                        continue;
                    } catch (NoSuchMethodException e) {
                        // that means there was no such method, proceed
                    }
                }

                // string shall be used directly, either to set or as constructor parameter (if suitable)
                try {
                    beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field);
                    continue;
                } catch (NoSuchMethodException e) {
                    // that means there was no such method, proceed
                }
                // or maybe there is method with suitable parameter?
                if (clazz.isPrimitive() && primitves.get(clazz) != null) {
                    clazz = primitves.get(clazz);
                }
                try {
                    method.invoke(value, clazz.getConstructor(String.class).newInstance(field));
                } catch (NoSuchMethodException nsme) {
                    // we are failed here,  but so what? be lenient
                }

            }
            // we are done with string
            else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) {
                // JSON array corresponds either to array type, or to some collection
                if (field instanceof JSONObject) {
                    JSONArray array = new JSONArray();
                    array.put(field);
                    field = array;
                }

                // we are interested in arrays for now
                if (clazz.isArray()) {
                    // populate field value from JSON Array
                    Object fieldValue = populateRecursive(clazz, field);
                    method.invoke(value, fieldValue);
                } else if (clazz.isAssignableFrom(List.class)) {
                    try {
                        Type type = method.getGenericParameterTypes()[0];
                        if (type instanceof ParameterizedType) {
                            Type param = ((ParameterizedType) type).getActualTypeArguments()[0];
                            if (param instanceof Class) {
                                Class c = (Class) param;

                                // populate field value from JSON Array
                                Object fieldValue = populateRecursiveList(clazz, c, field);
                                method.invoke(value, fieldValue);
                            }
                        }
                    } catch (Exception e) {
                        // failed
                    }
                }

            } else if (field instanceof JSONObject) {
                // JSON object means nested bean - process recursively
                method.invoke(value, unmarshall((JSONObject) field, clazz));
            } else if (clazz.equals(Date.class)) {
                method.invoke(value, new Date((Long) field));
            } else {

                // fallback here,  types not yet processed will be
                // set directly ( if possible )
                // TODO: guard this? for better leniency
                method.invoke(value, field);
            }

        }
    }
    return value;
}