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.codehaus.groovy.grails.commons.GrailsClassUtils.java

/**
 * Checks whether the given class is a JDK 1.5 enum.
 *
 * @param type The class to check/*from   w  ww .ja v a2 s  .c  o  m*/
 * @return true if it is an enum
 * @deprecated
 */
public static boolean isJdk5Enum(Class<?> type) {
    return type.isEnum();
}

From source file:de.unentscheidbar.validation.DefaultMessageTextGetterTest.java

@Test
public void testDefaultMessageTexts() {

    Locale[] locales = { Locale.ROOT, Locale.GERMAN };

    Reflections r = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(ClassUtils.getPackageName(Validators.class)))
            .setScanners(new ResourcesScanner(), new SubTypesScanner(false)));

    Collection<Class<? extends Id>> defaultMessageClasses = Collections2.filter(
            r.getSubTypesOf(ValidationMessage.Id.class), Predicates.and(IS_NOT_ABSTRACT, IsTestClass.NO));
    Assert.assertTrue("Suspiciously few message ID classes found", defaultMessageClasses.size() > 10);

    MessageTextGetter mtg = Validation.defaultMessageTextGetter();

    for (Class<? extends Id> idClass : defaultMessageClasses) {
        /* only works with enums atm (all default message ids are enums) */
        if (!idClass.isEnum()) {
            Assert.fail("Cannot test " + idClass.getName());
        }/*from w w  w  . j  a  v  a 2s  .c  o  m*/
        for (Id id : idClass.getEnumConstants()) {
            for (Locale locale : locales) {
                Assert.assertTrue("Missing default message text for " + locale + " -> "
                        + id.getClass().getName() + " -> " + id.name(), mtg.hasText(id, locale));
            }
        }
    }
}

From source file:org.sleeksnap.Configuration.java

@SuppressWarnings("unchecked")
public <T> T getEnumValue(final String key, final Class<?> class1) {
    if (class1.isEnum()) {
        return (T) class1.getEnumConstants()[getInteger(key)];
    }// ww  w .  j  a  v  a2  s  .  c  o m
    return null;
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?//from   w  ww.j a v  a  2s  . c  om
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}

From source file:com.google.walkaround.util.server.flags.JsonFlags.java

@VisibleForTesting
@SuppressWarnings("unchecked")
static Object parseOneFlag(FlagDeclaration decl, JSONObject json) throws FlagFormatException {
    String key = decl.getName();//from  w  w  w . j a va2  s  .c o  m
    Class<?> type = decl.getType();
    try {
        if (!json.has(key)) {
            throw new FlagFormatException("Missing flag: " + key);
        }
        // Explicit check, otherwise null would be interpreted as "null" (the
        // string) for string and enum values.
        if (json.isNull(key)) {
            throw new FlagFormatException("Null value for key " + key);
        }

        if (type == String.class) {
            return json.getString(key);
        } else if (type == Boolean.class) {
            return Boolean.valueOf(json.getBoolean(key));
        } else if (type == Integer.class) {
            int val = json.getInt(key);
            if (val != json.getDouble(key)) {
                throw new FlagFormatException(
                        "Loss of precision for type int, key=" + key + ", value=" + json.getDouble(key));
            }
            return Integer.valueOf(val);
        } else if (type == Double.class) {
            return Double.valueOf(json.getDouble(key));
        } else if (type.isEnum()) {
            // TODO(ohler): Avoid unchecked warning here, the rest of the method should be clean.
            return parseEnumValue(type.asSubclass(Enum.class), key, json.getString(key).toUpperCase());
        } else {
            throw new IllegalArgumentException("Unknown flag type " + type.getName());
        }
    } catch (JSONException e) {
        throw new FlagFormatException(
                "Invalid flag JSON for key " + key + " (possibly a bad type); map=" + json, e);
    }
}

From source file:springfox.documentation.schema.TypeNameExtractor.java

private String simpleTypeName(ResolvedType type, ModelContext context) {
    Class<?> erasedType = type.getErasedType();
    if (type instanceof ResolvedPrimitiveType) {
        return typeNameFor(erasedType);
    } else if (erasedType.isEnum()) {
        return "string";
    } else if (type instanceof ResolvedArrayType) {
        GenericTypeNamingStrategy namingStrategy = context.getGenericNamingStrategy();
        return String.format("Array%s%s%s", namingStrategy.getOpenGeneric(),
                simpleTypeName(type.getArrayElementType(), context), namingStrategy.getCloseGeneric());
    } else if (type instanceof ResolvedObjectType) {
        String typeName = typeNameFor(erasedType);
        if (typeName != null) {
            return typeName;
        }//from ww  w . j  a  v a 2 s .  c o m
    }
    return typeName(new ModelNameContext(type.getErasedType(), context.getDocumentationType()));
}

From source file:org.makersoft.mvc.builder.PackageBasedUrlPathBuilder.java

/**
 * Interfaces, enums, annotations, and abstract classes cannot be instantiated.
 * //from w w  w.  jav a 2s  .c o  m
 * @param controllerClass
 *            class to check
 * @return returns true if the class cannot be instantiated or should be ignored
 */
protected boolean cannotInstantiate(Class<?> controllerClass) {
    return controllerClass.isAnnotation() || controllerClass.isInterface() || controllerClass.isEnum()
            || (controllerClass.getModifiers() & Modifier.ABSTRACT) != 0 || controllerClass.isAnonymousClass();
}

From source file:com.xyxy.platform.modules.core.web.taglib.BSAbstractMultiCheckedElementTag.java

/**
 * Copy & Paste, ./*w  w w  . ja va2  s . c o m*/
 */
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
    Object items = getItems();
    Object itemsObject = (items instanceof String ? evaluate("items", items) : items);

    String itemValue = getItemValue();
    String itemLabel = getItemLabel();
    String valueProperty = (itemValue != null ? ObjectUtils.getDisplayString(evaluate("itemValue", itemValue))
            : null);
    String labelProperty = (itemLabel != null ? ObjectUtils.getDisplayString(evaluate("itemLabel", itemLabel))
            : null);

    Class<?> boundType = getBindStatus().getValueType();
    if ((itemsObject == null) && (boundType != null) && boundType.isEnum()) {
        itemsObject = boundType.getEnumConstants();
    }

    if (itemsObject == null) {
        throw new IllegalArgumentException(
                "Attribute 'items' is required and must be a Collection, an Array or a Map");
    }

    if (itemsObject.getClass().isArray()) {
        Object[] itemsArray = (Object[]) itemsObject;
        for (int i = 0; i < itemsArray.length; i++) {
            Object item = itemsArray[i];
            writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i);
        }
    } else if (itemsObject instanceof Collection) {
        final Collection optionCollection = (Collection) itemsObject;
        int itemIndex = 0;
        for (Iterator it = optionCollection.iterator(); it.hasNext(); itemIndex++) {
            Object item = it.next();
            writeObjectEntry(tagWriter, valueProperty, labelProperty, item, itemIndex);
        }
    } else if (itemsObject instanceof Map) {
        final Map optionMap = (Map) itemsObject;
        int itemIndex = 0;
        for (Iterator it = optionMap.entrySet().iterator(); it.hasNext(); itemIndex++) {
            Map.Entry entry = (Map.Entry) it.next();
            writeMapEntry(tagWriter, valueProperty, labelProperty, entry, itemIndex);
        }
    } else {
        throw new IllegalArgumentException("Attribute 'items' must be an array, a Collection or a Map");
    }

    return SKIP_BODY;
}

From source file:wwutil.jsoda.DataUtil.java

/** Check whether a value/valueType can be encoded, so that it can be used as condition value in query. */
static boolean canBeEncoded(Object value, Class valueType) {
    if (value == null)
        return true;

    if (valueType == String.class)
        return true;

    // Stringify basic type and encode them for sorting.
    if (valueType == Byte.class || valueType == byte.class) {
        return true;
    } else if (valueType == Short.class || valueType == short.class) {
        return true;
    } else if (valueType == Integer.class || valueType == int.class) {
        return true;
    } else if (valueType == Long.class || valueType == long.class) {
        return true;
    } else if (valueType == Float.class || valueType == float.class) {
        return true;
    } else if (valueType == Double.class || valueType == double.class) {
        return true;
    } else if (valueType == Boolean.class || valueType == boolean.class) {
        return true;
    } else if (valueType == Character.class || valueType == char.class) {
        return true;
    } else if (valueType == Date.class) {
        return true;
    } else if (valueType.isEnum()) {
        return true;
    }//from   w  ww.ja v a2 s  .  c om

    // JSON string value should not be used in query condition.
    return false;
}

From source file:com.medigy.persist.util.HibernateConfiguration.java

public void registerReferenceEntitiesAndCaches() {
    final Iterator classMappings = getClassMappings();
    while (classMappings.hasNext()) {
        Class aClass = ((PersistentClass) classMappings.next()).getMappedClass(); //(Class) classMappings.next();
        if (ReferenceEntity.class.isAssignableFrom(aClass)) {
            boolean foundCache = false;
            for (final Class ic : aClass.getClasses()) {
                if (CachedReferenceEntity.class.isAssignableFrom(ic)) {
                    if (ic.isEnum()) {
                        referenceEntitiesAndCachesMap.put(aClass, ic);
                        foundCache = true;
                    } else
                        throw new HibernateException(ic + " must be an enum since " + aClass + " is a "
                                + ReferenceEntity.class.getName());

                    break;
                }//from   w w w  . jav  a 2  s .  c  om

            }

            if (!foundCache)
                log.warn(aClass
                        + " is marked as a ReferenceEntity but does not contain a ReferenceEntityCache enum.");

            // TODO: find out how to ensure the new mapping for reference type is immutable and read only
            // final PersistentClass pClass = getClassMapping(aClass.getLabel());
        } else if (CustomReferenceEntity.class.isAssignableFrom(aClass)) {
            for (final Class ic : aClass.getClasses()) {
                if (CachedCustomReferenceEntity.class.isAssignableFrom(ic)) {
                    if (ic.isEnum()) {
                        customReferenceEntitiesAndCachesMap.put(aClass, ic);
                    } else
                        throw new HibernateException(ic + " must be an enum since " + aClass + " is a "
                                + CachedCustomReferenceEntity.class.getName());

                    break;
                }
            }
            // if no cache is found, its ok since these are custom
        }
    }
}