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.feilong.commons.core.lang.ClassUtil.java

/**
 *  class info map for log.//  w ww  . j  a v  a  2 s. c o  m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    //"clz.getCanonicalName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getSimpleName()": "DatePattern",

    // getCanonicalName ( Java Language Specification ??) && getName
    //??class?array?
    // getName[[Ljava.lang.String?getCanonicalName?
    map.put("clz.getCanonicalName()", klass.getCanonicalName());
    map.put("clz.getName()", klass.getName());
    map.put("clz.getSimpleName()", klass.getSimpleName());

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?? voidboolean?byte?char?short?int?long?float  double?
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ??,
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ????,??????
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class????java??false?trueJVM???java??????
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
    //      Class<?> klass = this.getClass();
    //
    //      TypeVariable<?>[] typeParameters = klass.getTypeParameters();
    //      TypeVariable<?> typeVariable = typeParameters[0];
    //
    //      Type[] bounds = typeVariable.getBounds();
    //
    //      Type bound = bounds[0];
    //
    //      if (log.isDebugEnabled()){
    //         log.debug("" + (bound instanceof ParameterizedType));
    //      }
    //
    //      Class<T> modelClass = ReflectUtil.getGenericModelClass(klass);
    //      return modelClass;
}

From source file:com.amazonaws.hal.client.ConversionUtil.java

private static Object convertFromNumber(Class<?> clazz, Number value) {
    if (String.class.isAssignableFrom(clazz)) {
        return value.toString();
    } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) {
        return value.intValue();
    } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) {
        return value.longValue();
    } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) {
        return value.shortValue();
    } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) {
        return value.doubleValue();
    } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
        return value.floatValue();
    } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) {
        return Boolean.valueOf(value.toString());
    } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) {
        if (value.longValue() <= 255) {
            return (char) value.longValue();
        } else {//from  www .  j av  a2 s . c o  m
            throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
        }
    } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) {
        return value.byteValue();
    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
        return new BigDecimal(value.toString());
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to
        // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2)
        return new BigInteger(String.valueOf(value.longValue()));
    } else if (Date.class.isAssignableFrom(clazz)) {
        return new Date(value.longValue());
    } else if (clazz.isEnum()) {
        try {
            //noinspection unchecked
            return Enum.valueOf((Class<Enum>) clazz, value.toString());
        } catch (IllegalArgumentException e) {
            log.error(String.format(
                    "'%s' is not a recognized enum value for %s.  Returning default of %s instead.", value,
                    clazz.getName(), clazz.getEnumConstants()[0]));

            return clazz.getEnumConstants()[0];
        }
    } else {
        throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
    }
}

From source file:org.rhq.scripting.javascript.JavascriptCompletor.java

/**
 * Look through all available contexts to find bindings that both start with
 * the supplied start and match the typeFilter.
 * @param start//from w  w  w  . ja v  a 2 s  .co  m
 * @param typeFilter
 * @return
 */
private Map<String, Object> getContextMatches(String start, Class<?> typeFilter) {
    Map<String, Object> found = new HashMap<String, Object>();
    if (context != null) {
        for (int scope : context.getScopes()) {
            Bindings bindings = context.getBindings(scope);
            for (String var : bindings.keySet()) {
                if (var.startsWith(start)) {

                    if ((bindings.get(var) != null && typeFilter.isAssignableFrom(bindings.get(var).getClass()))
                            || recomplete == 3) {
                        found.put(var, bindings.get(var));
                    }
                }
            }
        }

        if (typeFilter.isEnum()) {
            for (Object ec : typeFilter.getEnumConstants()) {
                Enum<?> e = (Enum<?>) ec;
                String code = typeFilter.getSimpleName() + "." + e.name();
                if (code.startsWith(start)) {
                    found.put(typeFilter.getSimpleName() + "." + e.name(), e);
                }
            }
        }
    }
    return found;
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception {
    Object result = null;//from  w w  w .  j ava  2s . c  o  m

    if (parameterTree == null) {
        return null;
    }

    if (genericType == null) {
        genericType = type.getGenericSuperclass();
    }

    Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray();
    Map<String, ParameterTree> parameterObject = parameterTree.getObject();
    Object value = parameterTree.getValue();

    Converter lookup = converter.lookup(type);
    if (lookup != null) {

        // converter found, use it
        result = lookup.convert(type, value);
        return result;
    }

    // Manage enums
    if (type.isEnum()) {
        Object name = value == null ? null : ((Object[]) value)[0];
        if (name != null) {
            result = Enum.valueOf((Class<? extends Enum>) type, name.toString());
        }

        // Manage collection
    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object converted = convert(object, convertType, null);
                instance.add(converted);
            }
        } else {
            Object[] tab = (Object[]) value;
            for (Object object : tab) {
                Object converted = converter.convert(object, convertType);
                instance.add(converted);
            }
        }

        result = instance;

        // Manage map
    } else if (Map.class.isAssignableFrom(type)) {
        Map instance;
        if (type.isInterface()) {
            if (SortedMap.class.isAssignableFrom(type)) {
                instance = new TreeMap();

            } else {
                instance = new HashMap();
            }
        } else {
            instance = (Map) type.newInstance();
        }

        Class convertKeyType = String.class;
        Class convertValueType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0];
            convertValueType = (Class) parameterizedType.getActualTypeArguments()[1];
        }

        for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
            String mapKey = entry.getKey();
            ParameterTree mapValue = entry.getValue();

            Object convertedKey = converter.convert(mapKey, convertKeyType);
            Object convertedValue = convert(mapValue, convertValueType, null);

            instance.put(convertedKey, convertedValue);
        }

        result = instance;

        // Manage simple object
    } else if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        if (parameterObject != null) {
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size());
            result = tabConverted;

            int index = 0;
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object objectConverted = convert(object, componentType, null);
                tabConverted[index] = objectConverted;
                index++;
            }

        } else {
            Object[] tab = (Object[]) value;
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length);
            result = tabConverted;

            for (int index = 0; index < tab.length; index++) {
                Object object = tab[index];
                Object objectConverted = converter.convert(object, componentType);
                tabConverted[index] = objectConverted;
            }
        }

    } else if (value instanceof UploadFile) {
        if (File.class.isAssignableFrom(type)) {
            UploadFile uploadFile = (UploadFile) value;
            result = uploadFile.getFile();
        } else {
            result = value;
        }

        // Manage simple object
    } else {
        Object instance = type.newInstance();
        boolean one = false;

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) {
                String attributeName = attribut.getKey();
                ParameterTree attributeValue = attribut.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValue, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (parameterArray != null) {
            for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) {
                String attributeName = entry.getKey();
                List<ParameterTree> attributeValues = entry.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValues, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (one) {
            result = instance;

        } else {
            result = null;
        }
    }

    return result;
}

From source file:org.wrml.runtime.schema.DefaultSchemaLoader.java

@Override
public final URI getTypeUri(final Type type) {

    if (type instanceof Class<?>) {
        final Class<?> clazz = (Class<?>) type;
        return getTypeUri(clazz.getCanonicalName(), clazz.isEnum(), true);
    } else {/*from  w w  w .  j av a2s  . co m*/
        // Get this schema id associated with the *slotted* schema. A slotted schema has one or more "open"
        // {@link Slot}s. Other (programming) languages refer to this type system concept as "parameterized",
        // "generic", or "templated" types.
        /*
         * // A slotted schema
         * final Context context = getContext();
         * final ApiLoader apiLoader = context.getApiLoader();
         * final ParameterizedType parameterizedType = (ParameterizedType) type;
         * final Class<?> slottedSchemaInterface = (Class<?>) parameterizedType.getRawType();
         * final URI slottedSchemaUri = getTypeUri(slottedSchemaInterface);
         *
         * final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(parameterizedType);
         * for (final TypeVariable<?> typeVar : typeArguments.keySet())
         * {
         * final Type slotSchemaType = typeArguments.get(typeVar);
         * final URI slotSchemaUri = getTypeUri(slotSchemaType);
         * final URI urlEncodedSlotSchemaUri = RestUtils.encodeUri(slotSchemaUri);
         * final String queryParam = typeVar.getName() + "=" + urlEncodedSlotSchemaUri;
         */

        throw new SchemaLoaderException(
                "Slotted schemas are not supported in this version; cannot associate a schema URI with type: "
                        + type,
                null, this);
    }
}

From source file:uk.co.q3c.v7.base.navigate.TextReaderSitemapProvider.java

@SuppressWarnings("unchecked")
private void validateLabelKeys() {
    boolean valid = true;
    Class<?> requestedLabelKeysClass = null;
    try {/*from   w ww. ja v  a 2 s  . c  o  m*/

        requestedLabelKeysClass = Class.forName(labelKeys);
        // enum
        if (!requestedLabelKeysClass.isEnum()) {
            valid = false;
        }

        // instance of I18NKeys
        @SuppressWarnings("rawtypes")
        Class<I18NKey> i18nClass = I18NKey.class;
        if (!i18nClass.isAssignableFrom(requestedLabelKeysClass)) {
            valid = false;
            labelClassNotI18N = true;
            log.warn(labelKeys + " does not implement I18NKeys");
        }
    } catch (ClassNotFoundException e) {
        valid = false;
        labelClassNonExistent = true;
        log.warn(labelKeys + " does not exist on the classpath");
    }
    if (!valid) {
        log.warn(labelKeys + " is not a valid enum class for I18N labels");
        this.labelClassNotI18N = true;
    } else {
        labelKeysClass = (Class<? extends Enum<?>>) requestedLabelKeysClass;
        lkfn = new LabelKeyForName(labelKeysClass);
    }
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

/**
 * Checks whether the type is SimpleType (mapped by
 * {@link SimpleTypeMappings}), Collection or Iterable (for mapping arrays),
 * Void type (returning null), or custom Class (for mapping objects).
 *
 * @param type//from   w  w  w  . j  a  v  a2 s  .  c o m
 * @param schema
 * @return the full schema represented as an ObjectNode.
 */
protected <T> ObjectNode checkAndProcessType(Class<T> type, ObjectNode schema) throws TypeException {
    String s = SimpleTypeMappings.forClass(type);
    // If it is a simple type, then just put the type
    if (s != null) {
        schema.put(TAG_TYPE, s);
    }
    // If it is a Collection or Iterable the generate the schema as an array
    else if (Iterable.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type)) {
        checkAndProcessCollection(type, schema);
    }
    // If it is void then return null
    else if (type == Void.class || type == void.class) {
        schema = null;
    }
    // If it is an Enum than process like enum
    else if (type.isEnum()) {
        processEnum(type, schema);
    }
    // If none of the above possibilities were true, then it is a custom object
    else {
        schema = processCustomType(type, schema);
    }
    return schema;
}

From source file:org.fourthline.cling.model.action.MethodActionExecutor.java

protected Object[] createInputArgumentValues(ActionInvocation<LocalService> actionInvocation, Method method)
        throws ActionException {

    LocalService service = actionInvocation.getAction().getService();

    Object[] values = new Object[actionInvocation.getAction().getInputArguments().length];
    int i = 0;//from   www.  ja v a  2  s.  c o  m
    for (ActionArgument<LocalService> argument : actionInvocation.getAction().getInputArguments()) {

        Class methodParameterType = method.getParameterTypes()[i];

        ActionArgumentValue<LocalService> inputValue = actionInvocation.getInput(argument);

        // If it's a primitive argument, we need a value
        if (methodParameterType.isPrimitive() && (inputValue == null || inputValue.toString().length() == 0))
            throw new ActionException(ErrorCode.ARGUMENT_VALUE_INVALID, "Primitive action method argument '"
                    + argument.getName() + "' requires input value, can't be null or empty string");

        // It's not primitive and we have no value, that's fine too
        if (inputValue == null) {
            values[i++] = null;
            continue;
        }

        // If it's not null, maybe it was a string-convertible type, if so, try to instantiate it
        String inputCallValueString = inputValue.toString();
        // Empty string means null and we can't instantiate Enums!
        if (inputCallValueString.length() > 0 && service.isStringConvertibleType(methodParameterType)
                && !methodParameterType.isEnum()) {
            try {
                Constructor<String> ctor = methodParameterType.getConstructor(String.class);
                log.finer("Creating new input argument value instance with String.class constructor of type: "
                        + methodParameterType);
                Object o = ctor.newInstance(inputCallValueString);
                values[i++] = o;
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
                throw new ActionException(ErrorCode.ARGUMENT_VALUE_INVALID,
                        "Can't convert input argment string to desired type of '" + argument.getName() + "': "
                                + ex);
            }
        } else {
            // Or if it wasn't, just use the value without any conversion
            values[i++] = inputValue.getValue();
        }
    }
    return values;
}

From source file:org.wrml.runtime.schema.DefaultSchemaLoader.java

private Class<?> getNativeChoicesEnumClass(final URI uri) {

    if (!_ChoicesEnumClasses.containsKey(uri)) {

        final ClassLoader parentClassLoader = getParent();
        if (parentClassLoader == null) {
            return null;

        }/* www  . ja  v a 2s  .  c  o  m*/

        final String choicesEnumName = getNativeTypeName(uri);

        try {
            final Class<?> choicesEnumClass = parentClassLoader.loadClass(choicesEnumName);
            if (choicesEnumClass != null && choicesEnumClass.isEnum()) {
                _ChoicesEnumClasses.put(uri, choicesEnumClass);
            }
        } catch (final ClassNotFoundException e) {
            return null;
        }

    }

    return _ChoicesEnumClasses.get(uri);

}

From source file:nz.co.senanque.vaadinsupport.MaduraPropertyWrapper.java

public void setValue(Object newValue) {
    if (isReadOnly()) {
        return;/*from   w ww  .j a v  a2 s . c  om*/
    }
    try {
        Class<?> clazz = this.getDataType();
        Object converted = newValue;
        if (m_propertyFormatter != null) {
            try {
                converted = m_propertyFormatter.parse(String.valueOf(newValue));
            } catch (Exception e) {
                MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
                String message = messageSourceAccessor.getMessage(
                        "nz.co.senanque.validationengine.numericparse",
                        new Object[] { this.m_label, String.valueOf(newValue) });
                throw new ValidationException(message);
            }
        } else {
            if (converted instanceof ChoiceBase) {
                converted = ((ChoiceBase) converted).getKey();
            }
            if (clazz != String.class) {
                try {
                    if (clazz.isEnum()) {
                        Method fromValueMethod = clazz.getMethod("fromValue", String.class);
                        converted = fromValueMethod.invoke(null, new Object[] { String.valueOf(newValue) });
                    } else {
                        MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(
                                m_messageSource);
                        converted = ConvertUtils.convertToObject(clazz, newValue, messageSourceAccessor);
                    }
                } catch (Exception e) {
                    throw e;
                }
            }
        }
        m_setter.invoke(m_owner, new Object[] { converted });
        setErrorText(null);
        m_lastFailedValue = null;
    } catch (InvocationTargetException e) {
        logger.warn("error", e);
        Throwable target = e.getTargetException();
        if (target != null) {
            if (target instanceof ValidationException) {
                setErrorText(target.getLocalizedMessage());
                m_lastFailedValue = newValue;
            } else {
                throw new RuntimeException(target);
            }
        } else {
            throw new RuntimeException(e);
        }
    } catch (ValidationException e) {
        logger.warn("error", e);
        setErrorText(e.getLocalizedMessage());
        m_lastFailedValue = newValue;
    } catch (Exception e) {
        logger.warn("error", e);
        throw new RuntimeException(e);
    }
}