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.apache.hadoop.yarn.api.TestPBImplRecords.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object genTypeValue(Type type) {
    Object ret = typeValueCache.get(type);
    if (ret != null) {
        return ret;
    }//from   w  w  w  .java  2s .com
    // only use positive primitive values
    if (type.equals(boolean.class)) {
        return rand.nextBoolean();
    } else if (type.equals(byte.class)) {
        return bytes[rand.nextInt(4)];
    } else if (type.equals(int.class)) {
        return rand.nextInt(1000000);
    } else if (type.equals(long.class)) {
        return Long.valueOf(rand.nextInt(1000000));
    } else if (type.equals(float.class)) {
        return rand.nextFloat();
    } else if (type.equals(double.class)) {
        return rand.nextDouble();
    } else if (type.equals(String.class)) {
        return String.format("%c%c%c", 'a' + rand.nextInt(26), 'a' + rand.nextInt(26), 'a' + rand.nextInt(26));
    } else if (type instanceof Class) {
        Class clazz = (Class) type;
        if (clazz.isArray()) {
            Class compClass = clazz.getComponentType();
            if (compClass != null) {
                ret = Array.newInstance(compClass, 2);
                Array.set(ret, 0, genTypeValue(compClass));
                Array.set(ret, 1, genTypeValue(compClass));
            }
        } else if (clazz.isEnum()) {
            Object[] values = clazz.getEnumConstants();
            ret = values[rand.nextInt(values.length)];
        } else if (clazz.equals(ByteBuffer.class)) {
            // return new ByteBuffer every time
            // to prevent potential side effects
            ByteBuffer buff = ByteBuffer.allocate(4);
            rand.nextBytes(buff.array());
            return buff;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type rawType = pt.getRawType();
        Type[] params = pt.getActualTypeArguments();
        // only support EnumSet<T>, List<T>, Set<T>, Map<K,V>
        if (rawType.equals(EnumSet.class)) {
            if (params[0] instanceof Class) {
                Class c = (Class) (params[0]);
                return EnumSet.allOf(c);
            }
        }
        if (rawType.equals(List.class)) {
            ret = Lists.newArrayList(genTypeValue(params[0]));
        } else if (rawType.equals(Set.class)) {
            ret = Sets.newHashSet(genTypeValue(params[0]));
        } else if (rawType.equals(Map.class)) {
            Map<Object, Object> map = Maps.newHashMap();
            map.put(genTypeValue(params[0]), genTypeValue(params[1]));
            ret = map;
        }
    }
    if (ret == null) {
        throw new IllegalArgumentException("type " + type + " is not supported");
    }
    typeValueCache.put(type, ret);
    return ret;
}

From source file:org.talend.components.netsuite.NetSuiteDatasetRuntimeImpl.java

/**
 * Infers an Avro schema for the given FieldDesc. This can be an expensive operation so the schema should be
 * cached where possible. The return type will be the Avro Schema that can contain the fieldDesc data without loss of
 * precision./*from  w w  w.  j a v a2 s . c om*/
 *
 * @param fieldDesc the <code>FieldDesc</code> to analyse.
 * @return the schema for data that the fieldDesc describes.
 */
public static Schema inferSchemaForField(FieldDesc fieldDesc) {
    Schema base;

    if (fieldDesc instanceof CustomFieldDesc) {
        CustomFieldDesc customFieldInfo = (CustomFieldDesc) fieldDesc;
        CustomFieldRefType customFieldRefType = customFieldInfo.getCustomFieldType();

        if (customFieldRefType == CustomFieldRefType.BOOLEAN) {
            base = AvroUtils._boolean();
        } else if (customFieldRefType == CustomFieldRefType.LONG) {
            base = AvroUtils._long();
        } else if (customFieldRefType == CustomFieldRefType.DOUBLE) {
            base = AvroUtils._double();
        } else if (customFieldRefType == CustomFieldRefType.DATE) {
            base = AvroUtils._logicalTimestamp();
        } else if (customFieldRefType == CustomFieldRefType.STRING) {
            base = AvroUtils._string();
        } else {
            base = AvroUtils._string();
        }

    } else {
        Class<?> fieldType = fieldDesc.getValueType();

        if (fieldType == Boolean.TYPE || fieldType == Boolean.class) {
            base = AvroUtils._boolean();
        } else if (fieldType == Integer.TYPE || fieldType == Integer.class) {
            base = AvroUtils._int();
        } else if (fieldType == Long.TYPE || fieldType == Long.class) {
            base = AvroUtils._long();
        } else if (fieldType == Float.TYPE || fieldType == Float.class) {
            base = AvroUtils._float();
        } else if (fieldType == Double.TYPE || fieldType == Double.class) {
            base = AvroUtils._double();
        } else if (fieldType == XMLGregorianCalendar.class) {
            base = AvroUtils._logicalTimestamp();
        } else if (fieldType == String.class) {
            base = AvroUtils._string();
        } else if (fieldType.isEnum()) {
            base = AvroUtils._string();
        } else {
            base = AvroUtils._string();
        }
    }

    base = fieldDesc.isNullable() ? AvroUtils.wrapAsNullable(base) : base;

    return base;
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanMarshaller.java

public void visit(Object bean, Handler<Object> handler) {
    if (bean == null) {
        return;/*w w  w.  j a va 2  s.  com*/
    }

    Class<? extends Object> beanClass = bean.getClass();

    handler.handle(bean);

    if (beanClass.isEnum() || beanClass.isPrimitive()) {
        //nothing more to do
        return;
    }

    // TODO: implement special handling for RawType, if necessary (it has no XmlType annotation any more)

    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        // no @XmlType annotation, we are not interested to go any deeper
        return;
    }

    List<String> propOrder = inspector.getPropOrder(beanClass);
    for (String fieldName : propOrder) {
        Method getter = inspector.findPropertyGetter(beanClass, fieldName);
        if (getter == null) {
            throw new IllegalStateException("No getter for field " + fieldName + " in " + beanClass);
        }
        Object getterResult = getValue(bean, getter, fieldName);

        if (getterResult == null) {
            continue;
        }

        if (getterResult instanceof Collection<?>) {
            Collection col = (Collection) getterResult;
            if (col.isEmpty()) {
                continue;
            }

            for (Object element : col) {
                visitValue(element, handler);

            }
        } else {
            visitValue(getterResult, handler);
        }
    }
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object resolveArg(Type type, String arg) throws MissingDomainObject {
    // type can be null in a few cases - nothing to be done about it?
    if (null == type) {
        return null;
    }/* w  w  w . j  a v  a2  s .c o  m*/

    // check for non-parameterized types
    if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, arg);
        } else {
            return resolveSimpleArg(clazz, arg);
        }
    }

    // check for collection, denoted by leading (
    if (type instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) type;
        Class<?> clazz = (Class<?>) ptype.getRawType();
        boolean isCollection = false;
        if (clazz.equals(Collection.class))
            isCollection = true;
        else {
            Class<?>[] ifs = clazz.getInterfaces();
            for (Class<?> ifc : ifs) {
                if (ifc.equals(Collection.class)) {
                    isCollection = true;
                    break;
                }
            }
        }
        if (isCollection) {
            // expect arg to start with "("
            log.debug("processing collection " + clazz.getName());
            if (arg.charAt(0) != '(') {
                log.error("Collection arg " + arg + " does not start with paren");
                return null;
            }
            // extract element type and resolve recursively
            Type[] tas = ptype.getActualTypeArguments();
            if (1 == tas.length) {
                Class<?> argClazz = (Class<?>) tas[0];
                // create an instance of the collection
                Collection<Object> coll;
                // resolve interfaces into actual classes
                if (clazz.isInterface())
                    clazz = ifImplementors.get(clazz);
                try {
                    coll = (Collection<Object>) clazz.newInstance();
                } catch (Exception e) {
                    log.error("Exception creating collection: " + e.toString());
                    return null;
                }
                // at this point, we can split the string and resolve recursively
                String body = arg.substring(1, arg.indexOf(')'));
                String[] items = body.split(",");
                for (String item : items) {
                    coll.add(resolveSimpleArg(argClazz, item));
                }
                return coll;
            }
        }
    }

    // if we get here, no resolution
    log.error("unresolved arg: type = " + type + ", arg = " + arg);
    return null;
}

From source file:uk.q3c.krail.core.navigate.sitemap.DefaultFileSitemapLoader.java

@SuppressWarnings("unchecked")
private void validateLabelKeys(String source) {
    boolean valid = true;
    Class<?> requestedLabelKeysClass = null;
    try {/* www. jav a 2s. c o m*/

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

        // instance of I18NKeys
        @SuppressWarnings("rawtypes")
        Class<I18NKey> i18nClass = I18NKey.class;
        if (!i18nClass.isAssignableFrom(requestedLabelKeysClass)) {
            valid = false;
            addError(source, LABELKEY_DOES_NOT_IMPLEMENT_I18N_KEY, labelKey);
        }
    } catch (ClassNotFoundException e) {
        valid = false;
        addError(source, LABELKEY_NOT_IN_CLASSPATH, labelKey);
    }
    if (!valid) {
        addError(source, LABELKEY_NOT_VALID_CLASS_FOR_I18N_LABELS, labelKey);
    } else {
        labelKeysClass = (Class<? extends Enum<?>>) requestedLabelKeysClass;
        lkfn = new LabelKeyForName(labelKeysClass);
    }
}

From source file:gov.va.vinci.leo.ae.LeoBaseAnnotator.java

/**
 * Returns parameters defined in a static class named Param with static ConfigurationParameter objects.
 * <p/>/*ww w.j a  v  a  2s . c  om*/
 * For Example:
 * <p/>
 * <pre>
 * {@code
 * protected String parameterName = "parameter value";
 *
 * public static class Param {
 *      public static ConfigurationParameter PARAMETER_NAME
 *          = new ConfigurationParameterImpl(
 *              "parameterName", "Description", "String", false, true, new String[] {}
 *          );
 * }
 * }</pre>
 *
 * @return  the annotator parameters this annotator can accept.
 * @throws IllegalAccessException  if there is an exception trying to get annotator parameters via reflection.
 */
protected ConfigurationParameter[] getAnnotatorParams() throws IllegalAccessException {
    ConfigurationParameter params[] = null;

    for (Class c : this.getClass().getDeclaredClasses()) {
        if (c.isEnum() && Arrays.asList(c.getInterfaces()).contains(ConfigurationParameter.class)) {
            params = new ConfigurationParameter[EnumSet.allOf(c).size()];
            int counter = 0;
            for (Object o : EnumSet.allOf(c)) {
                params[counter] = ((ConfigurationParameter) o);
                counter++;
            }
            break;
        } else if (c.getCanonicalName().endsWith(".Param")) {
            Field[] fields = c.getFields();
            List<ConfigurationParameter> paramList = new ArrayList<ConfigurationParameter>();

            for (Field f : fields) {
                if (ConfigurationParameter.class.isAssignableFrom(f.getType())) {
                    paramList.add((ConfigurationParameter) f.get(null));
                }
            }
            params = paramList.toArray(new ConfigurationParameter[paramList.size()]);
        }
    }
    return params;
}

From source file:com.google.api.server.spi.config.jsonwriter.JsonConfigWriter.java

/**
 * Adds an arbitrary, non-array type to a given schema config.
 *
 * @param schemasNode the config to store the generated type schema
 * @param type the type from which to generate a schema
 * @param enclosingType for bean properties, the enclosing bean type, used for resolving type
 *        variables/* w ww.  j  av a 2s  .  c  o m*/
 * @return the name of the schema generated from the type
 */
@VisibleForTesting
String addTypeToSchema(ObjectNode schemasNode, TypeToken<?> type, TypeToken<?> enclosingType,
        ApiConfig apiConfig, List<ApiParameterConfig> parameterConfigs) throws ApiConfigException {
    if (typeLoader.isSchemaType(type)) {
        return typeLoader.getSchemaType(type);
    } else if (Types.isObject(type)) {
        if (!schemasNode.has(ANY_SCHEMA_NAME)) {
            ObjectNode anySchema = objectMapper.createObjectNode();
            anySchema.put("id", ANY_SCHEMA_NAME);
            anySchema.put("type", "any");
            schemasNode.set(ANY_SCHEMA_NAME, anySchema);
        }
        return ANY_SCHEMA_NAME;
    } else if (Types.isMapType(type)) {
        if (!schemasNode.has(MAP_SCHEMA_NAME)) {
            ObjectNode mapSchema = objectMapper.createObjectNode();
            mapSchema.put("id", MAP_SCHEMA_NAME);
            mapSchema.put("type", "object");
            schemasNode.set(MAP_SCHEMA_NAME, mapSchema);
        }
        return MAP_SCHEMA_NAME;
    }

    // If we already have this schema defined, don't define it again!
    String typeName = Types.getSimpleName(type, apiConfig.getSerializationConfig());
    JsonNode existing = schemasNode.get(typeName);
    if (existing != null && existing.isObject()) {
        return typeName;
    }

    ObjectNode schemaNode = objectMapper.createObjectNode();
    Class<?> c = type.getRawType();
    if (c.isEnum()) {
        schemasNode.set(typeName, schemaNode);
        schemaNode.put("id", typeName);
        schemaNode.put("type", "string");

        ArrayNode enumNode = objectMapper.createArrayNode();
        for (Object enumConstant : c.getEnumConstants()) {
            enumNode.add(enumConstant.toString());
        }
        schemaNode.set("enum", enumNode);
    } else {
        // JavaBean
        TypeToken<?> serializedType = ApiAnnotationIntrospector.getSchemaType(type, apiConfig);
        if (!type.equals(serializedType)) {
            return addTypeToSchema(schemasNode, serializedType, enclosingType, apiConfig, parameterConfigs);
        } else {
            addBeanTypeToSchema(schemasNode, typeName, schemaNode, type, apiConfig, parameterConfigs);
        }
    }
    return typeName;
}

From source file:org.talend.mdm.repository.utils.Bean2EObjUtil.java

public Object convertFromEObj2Bean(EObject eObj) {
    EClass eCls = eObj.eClass();//w  w w. j  a  v a  2s  .  co m
    Class beanCls = (Class) classMap.getKey(eCls);
    if (beanCls != null) {
        Map<Object, Method[]> beanFieldMap = beanClassUtil.findFieldMap(beanCls);
        if (beanFieldMap == null) {
            return null;
        }

        try {
            if (beanCls.isEnum()) {
                EStructuralFeature feature = fieldMap.get(beanCls);
                if (feature != null) {
                    Method convertMethod = beanFieldMap.get(beanCls)[1];
                    Object value = eObj.eGet(feature);
                    try {
                        return convertMethod.invoke(null, value);
                    } catch (IllegalArgumentException e) {
                        log.error(e.getMessage(), e);
                    } catch (InvocationTargetException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else {
                Object bean = null;
                bean = beanCls.newInstance();

                for (Object fieldObj : beanFieldMap.keySet()) {
                    Field field = (Field) fieldObj;
                    try {
                        EStructuralFeature feature = fieldMap.get(field);
                        if (feature != null) {
                            Method setMethod = beanFieldMap.get(field)[1];

                            Object value = eObj.eGet(feature);
                            if (value != null) {
                                if (feature.isMany()) {
                                    EList list = (EList) value;
                                    if (beanClassUtil.isCollectionField(field)) {
                                        Object collectionObj = setMethod.invoke(bean);
                                        if (collectionObj instanceof Collection) {
                                            for (Object echildObj : list) {
                                                Object childObj = null;
                                                if (echildObj != null
                                                        && beanClassUtil.isJavaClass(echildObj.getClass())) {
                                                    childObj = echildObj;
                                                } else {
                                                    childObj = convertFromEObj2Bean((EObject) echildObj);
                                                }
                                                ((Collection) collectionObj).add(childObj);
                                            }
                                        }

                                    } else if (beanClassUtil.isArrayField(field)) {

                                        Object newInstance = Array
                                                .newInstance(field.getType().getComponentType(), list.size());
                                        Object[] children = (Object[]) newInstance;
                                        int i = 0;
                                        for (Object echildObj : list) {
                                            Object childObj = null;
                                            if (echildObj != null
                                                    && beanClassUtil.isJavaClass(echildObj.getClass())) {
                                                childObj = echildObj;
                                            } else {
                                                childObj = convertFromEObj2Bean((EObject) echildObj);
                                            }
                                            children[i] = childObj;
                                            i++;
                                        }
                                        setMethod.invoke(bean, newInstance);
                                    }

                                } else {
                                    Object eValue = null;
                                    if (beanClassUtil.isJavaField(field)) {
                                        eValue = value;
                                    } else {
                                        // a object reference
                                        eValue = convertFromEObj2Bean((EObject) value);
                                    }
                                    setMethod.invoke(bean, eValue);
                                }
                            }
                        }
                    } catch (IllegalArgumentException e) {
                        log.error(e.getMessage(), e);
                    } catch (IllegalAccessException e) {
                        log.error(e.getMessage(), e);
                    } catch (InvocationTargetException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                return bean;
            }
        } catch (InstantiationException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
    }
    return null;
}

From source file:com.alibaba.fastjson.parser.ParserConfig.java

/**
 * @deprecated  internal method, dont call
 */// www .  ja va 2 s  . c  om
public static boolean isPrimitive2(Class<?> clazz) {
    return clazz.isPrimitive() //
            || clazz == Boolean.class //
            || clazz == Character.class //
            || clazz == Byte.class //
            || clazz == Short.class //
            || clazz == Integer.class //
            || clazz == Long.class //
            || clazz == Float.class //
            || clazz == Double.class //
            || clazz == BigInteger.class //
            || clazz == BigDecimal.class //
            || clazz == String.class //
            || clazz == java.util.Date.class //
            || clazz == java.sql.Date.class //
            || clazz == java.sql.Time.class //
            || clazz == java.sql.Timestamp.class //
            || clazz.isEnum() //
    ;
}

From source file:com.bstek.dorado.data.JsonUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object internalToJavaEntity(ObjectNode objectNode, EntityDataType dataType, Class<?> targetType,
        boolean proxy, JsonConvertContext context) throws Exception {
    if (objectNode == null || objectNode.isNull()) {
        return null;
    }// ww w .  ja va 2s  .  c om

    Class<?> creationType = null;
    if (dataType != null && !(dataType instanceof CustomEntityDataType)) {
        creationType = dataType.getCreationType();
        if (creationType == null) {
            creationType = dataType.getMatchType();
        }
    }
    if (creationType == null) {
        creationType = Record.class;
    }

    Object result;
    if (EnhanceableEntity.class.isAssignableFrom(creationType)) {
        EnhanceableEntity ee = (EnhanceableEntity) creationType.newInstance();
        ee.setEntityEnhancer(new EnhanceableMapEntityEnhancer(dataType));
        result = ee;
    } else {
        MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(dataType, creationType,
                null);
        result = ProxyBeanUtils.createBean(creationType, mis);
    }

    EntityWrapper entity = EntityWrapper.create(result);
    if (proxy) {
        entity.setStateLocked(true);
    }

    Iterator<Entry<String, JsonNode>> fields = objectNode.getFields();
    while (fields.hasNext()) {
        Entry<String, JsonNode> field = fields.next();
        String property = field.getKey();
        if (property.charAt(0) == SYSTEM_PROPERTY_PREFIX) {
            continue;
        }

        Object value = null;
        JsonNode jsonNode = field.getValue();
        if (jsonNode != null && !jsonNode.isNull()) {
            Class<?> type = null;
            PropertyDef propertyDef = null;
            DataType propertyDataType = null;
            type = entity.getPropertyType(property);
            if (dataType != null) {
                propertyDef = dataType.getPropertyDef(property);
                if (propertyDef != null) {
                    propertyDataType = propertyDef.getDataType();
                }
            }

            if (jsonNode instanceof ContainerNode) {
                value = toJavaObject(jsonNode, propertyDataType, type, proxy, context);
            } else if (jsonNode instanceof ValueNode) {
                value = toJavaValue((ValueNode) jsonNode, propertyDataType, null);
            } else {
                throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
            }

            if (type != null) {
                if (!type.isInstance(value)) {
                    if (value instanceof String && type.isEnum()) {
                        if (StringUtils.isNotBlank((String) value)) {
                            value = Enum.valueOf((Class<? extends Enum>) type, (String) value);
                        }
                    } else {
                        propertyDataType = getDataTypeManager().getDataType(type);
                        if (propertyDataType != null) {
                            value = propertyDataType.fromObject(value);
                        }
                    }
                }
            } else {
                if (value instanceof String) { // ?
                    String str = (String) value;
                    if (str.length() == DEFAULT_DATE_PATTERN_LEN
                            && DEFAULT_DATE_PATTERN.matcher(str).matches()) {
                        value = DateUtils.parse(com.bstek.dorado.core.Constants.ISO_DATETIME_FORMAT1, str);
                    }
                }
            }
        }
        entity.set(property, value);
    }

    if (proxy) {
        entity.setStateLocked(false);
        int state = JsonUtils.getInt(objectNode, STATE_PROPERTY);
        if (state > 0) {
            entity.setState(EntityState.fromInt(state));
        }

        int entityId = JsonUtils.getInt(objectNode, ENTITY_ID_PROPERTY);
        if (entityId > 0) {
            entity.setEntityId(entityId);
        }

        ObjectNode jsonOldValues = (ObjectNode) objectNode.get(OLD_DATA_PROPERTY);
        if (jsonOldValues != null) {
            Map<String, Object> oldValues = entity.getOldValues(true);
            Iterator<Entry<String, JsonNode>> oldFields = jsonOldValues.getFields();
            while (oldFields.hasNext()) {
                Entry<String, JsonNode> entry = oldFields.next();
                String property = entry.getKey();
                PropertyDef propertyDef = null;
                DataType propertyDataType = null;
                Object value;

                if (dataType != null) {
                    propertyDef = dataType.getPropertyDef(property);
                    if (propertyDef != null) {
                        propertyDataType = propertyDef.getDataType();
                    }
                }

                if (dataType != null) {
                    propertyDef = dataType.getPropertyDef(property);
                    if (propertyDef != null) {
                        propertyDataType = propertyDef.getDataType();
                    }
                }

                JsonNode jsonNode = entry.getValue();
                if (jsonNode instanceof ContainerNode) {
                    Class<?> type = entity.getPropertyType(property);
                    value = toJavaObject(jsonNode, propertyDataType, type, proxy, context);
                } else if (jsonNode instanceof ValueNode) {
                    value = toJavaValue((ValueNode) jsonNode, propertyDataType, null);
                } else {
                    throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
                }

                oldValues.put(property, value);
            }
        }
    }

    if (targetType != null && !targetType.isInstance(result)) {
        throw new IllegalArgumentException("Java type mismatch. expect [" + targetType + "].");
    }
    if (context != null && context.getEntityCollection() != null) {
        context.getEntityCollection().add(result);
    }
    return result;
}