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:io.github.benas.randombeans.util.ReflectionUtils.java

/**
 * Check if a type is an enum type.//from  w ww .  j  a v a  2 s . c  om
 *
 * @param type the type to check.
 * @return true if the type is an enum type, false otherwise.
 */
public static boolean isEnumType(final Class<?> type) {
    return type.isEnum();
}

From source file:nz.co.senanque.validationengine.ConvertUtils.java

public static Object convertToObject(Class<?> clazz, Object obj, MessageSourceAccessor messageSourceAccessor) {
    try {//from  ww  w  . j av  a  2s .  c o  m
        return convertTo(clazz, obj);
    } catch (RuntimeException e) {
        if (clazz.isEnum()) {
            Object o;
            try {
                //                    Method[] methods = clazz.getMethods();
                Method fromValueMethod = clazz.getMethod("fromValue", String.class);
                final String oStr = String.valueOf(obj);
                o = fromValueMethod.invoke(null, oStr);
                return o;
            } catch (Exception e1) {
            }
        }
        if (messageSourceAccessor != null) {
            String message = messageSourceAccessor.getMessage(s_message,
                    new Object[] { obj.getClass().getSimpleName(), clazz.getSimpleName() });
            throw new ValidationException(message);
        } else {
            throw new RuntimeException(
                    "Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
        }
    }
}

From source file:io.lavagna.common.ConstructorAnnotationRowMapper.java

private static ColumnMapper findColumnAnnotationValue(Class<?> clazz, int position, Annotation[] annotations,
        Class<?> paramType) {

    for (Annotation a : annotations) {
        if (Column.class.isAssignableFrom(a.annotationType())) {

            String name = ((Column) a).value();

            if (paramType.isEnum()) {
                return new EnumColumnMapper(name, paramType);
            } else if (boolean.class == paramType || Boolean.class == paramType) {
                return new BooleanColumnMapper(name);
            } else {
                return new ColumnMapper(name);
            }/*from   www .j  a  va2 s .  c  om*/
        }
    }

    throw new IllegalStateException("No annotation @Column found for class: " + clazz.getName()
            + " in constructor at position " + position);
}

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

/**
 * Creates a map of all classes implementing the {@link com.medigy.persist.reference.custom.CustomReferenceEntity}
 * interface and the respective cached enums
 *
 * @return// w  w  w. j  a  v  a 2s.  co m
 */
protected static Map<Class, Class<? extends CachedCustomReferenceEntity>> getCustomReferenceEntitiesAndRespectiveEnums(
        final Iterator classMappings) {
    final Map<Class, Class<? extends CachedCustomReferenceEntity>> customReferenceEntitiesAndCachesMap = new HashMap<Class, Class<? extends CachedCustomReferenceEntity>>();
    while (classMappings.hasNext()) {
        Class aClass = ((PersistentClass) classMappings.next()).getMappedClass(); //(Class) classMappings.next();
        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
        }
    }
    return customReferenceEntitiesAndCachesMap;
}

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

protected static Map<Class, Class<? extends CachedReferenceEntity>> getReferenceEntitiesAndRespectiveEnums(
        final Iterator classMappings) {
    Map<Class, Class<? extends CachedReferenceEntity>> referenceEntitiesAndCachesMap = new HashMap<Class, Class<? extends CachedReferenceEntity>>();
    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  . ja  va  2s . 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());
        }
    }
    return referenceEntitiesAndCachesMap;

}

From source file:cc.kave.commons.utils.json.JsonUtils.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static void identifyHierarchiesAndRegisterAll(GsonBuilder gb, Class<?>[] eventsAndRelatedTypes) {
    Map<Class, Set<Class>> baseToSubs = Maps.newHashMap();

    for (Class<?> elem : eventsAndRelatedTypes) {
        if (elem.isEnum()) {
            registerEnum(gb, (Class<Enum>) elem);
            continue;
        }//from  w  w  w .j a  v  a2s .c o  m

        for (Class<?> base : getAllTypesFromHierarchyExceptObject(elem, false)) {
            Set<Class> subs = baseToSubs.get(base);
            if (subs == null) {
                subs = Sets.newHashSet();
                baseToSubs.put(base, subs);
            }
            subs.add(elem);
        }
        registerHierarchy(gb, elem, new Class[] { elem });
    }

    for (Class base : baseToSubs.keySet()) {
        Set<Class> subs = baseToSubs.get(base);
        Class[] arr = subs.toArray(new Class[0]);
        registerHierarchy(gb, base, arr);
    }
}

From source file:org.broadinstitute.gatk.queue.extensions.gatk.ArgumentField.java

/**
 * On primitive types returns the capitalized scala type.
 * @param argType The class to check for options.
 * @return the simple name of the class.
 */// w w w  .java2  s  . com
protected static String getType(Class<?> argType) {
    // Special case for enums.
    // Return the full path as sometimes two enums
    // used in the same class have the same name
    // ex: Model and Model
    if (argType.isEnum())
        return argType.getName().replace("$", ".");

    String type = argType.getSimpleName();

    if (argType.isPrimitive())
        type = StringUtils.capitalize(type);

    if ("Integer".equals(type))
        type = "Int";

    return type;
}

From source file:MyClass.java

public static String getClassDescription(Class c) {
    StringBuilder classDesc = new StringBuilder();
    int modifierBits = 0;
    String keyword = "";
    if (c.isInterface()) {
        modifierBits = c.getModifiers() & Modifier.interfaceModifiers();
        if (c.isAnnotation()) {
            keyword = "@interface";
        } else {/*from w w w.j  a  v  a 2  s  . c o m*/
            keyword = "interface";
        }
    } else if (c.isEnum()) {
        modifierBits = c.getModifiers() & Modifier.classModifiers();
        keyword = "enum";
    }
    modifierBits = c.getModifiers() & Modifier.classModifiers();
    keyword = "class";

    String modifiers = Modifier.toString(modifierBits);
    classDesc.append(modifiers);
    classDesc.append(" " + keyword);
    String simpleName = c.getSimpleName();
    classDesc.append(" " + simpleName);

    String genericParms = getGenericTypeParams(c);
    classDesc.append(genericParms);

    Class superClass = c.getSuperclass();
    if (superClass != null) {
        String superClassSimpleName = superClass.getSimpleName();
        classDesc.append("  extends " + superClassSimpleName);
    }
    String interfaces = Main.getClassInterfaces(c);
    if (interfaces != null) {
        classDesc.append("  implements " + interfaces);
    }
    return classDesc.toString();
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Check if the given type represents a "simple" value type:
 * a primitive, a String or other CharSequence, a Number, a Date,
 * a URI, a URL, a Locale or a Class.//from   w w w.  j ava 2 s.c o  m
 * @param clazz the type to check
 * @return whether the given type represents a "simple" value type
 */
public static boolean isSimpleValueType(Class<?> clazz) {
    return ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum()
            || CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz)
            || Date.class.isAssignableFrom(clazz) || clazz.equals(URI.class) || clazz.equals(URL.class)
            || clazz.equals(Locale.class) || clazz.equals(Class.class);
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MappingHelper.java

/**
 * Bildet ein Objekt mithilfe von Dozer auf einen gewnschten Zieltyp ab. Im Gegensatz zu
 * {@link Mapper#map(Object, Class)} knnen als Zieltyp auch generische Collections, String und primitive
 * Typen bergeben werden./* w ww  .  j a va  2s  .  com*/
 * 
 * @param mapper
 *            der Dozer-Mapper
 * @param source
 *            das zu mappende Objekt
 * @param destinationType
 *            der Zieltyp
 * @return das gemappte Objekt
 */
@SuppressWarnings("unchecked")
public static Object map(Mapper mapper, Object source, Type destinationType) {
    if (source == null) {
        return null;
    }

    if (destinationType instanceof ParameterizedType) {
        ParameterizedType parDestinationType = (ParameterizedType) destinationType;

        Class<?> rawClass = (Class<?>) parDestinationType.getRawType();
        if (List.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new ArrayList<Object>());
        } else if (SortedSet.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new TreeSet<Object>());
        } else if (Set.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new HashSet<Object>());
        } else if (SortedMap.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new TreeMap<Object, Object>());
        } else if (Map.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new HashMap<Object, Object>());
        }

        destinationType = parDestinationType.getRawType();
    }

    if (destinationType instanceof GenericArrayType) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }

        // wir werden im Array Element pro Element mappen
        Type elementType = ((GenericArrayType) destinationType).getGenericComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    } else if ((destinationType instanceof Class<?>) && ((Class<?>) destinationType).isArray()) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }
        Class<?> destinationTypeClass = (Class<?>) destinationType;
        // wir werden im Array Element pro Element mappen
        Type elementType = destinationTypeClass.getComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    }

    if (!(destinationType instanceof Class<?>)) {
        throw new IllegalArgumentException(
                "Ein Mapping auf Typ " + destinationType + " wird nicht untersttzt");
    }

    Class<?> destinationClass = (Class<?>) destinationType;

    if (ClassUtils.isPrimitiveOrWrapper(destinationClass) || MAPPING_BLACKLIST.contains(destinationClass)) {
        return source;
    } else if (destinationClass.isEnum()) {
        // wir mssen auf dieser Ebene Enums leider manuell mappen
        if (!(source instanceof Enum)) {
            throw new IllegalArgumentException("Ein Mapping auf ein Enum " + destinationClass
                    + " wird nicht untersttzt, da das Quellobjekt kein Enumobjekt ist (Quellobjektstyp: "
                    + source.getClass().toString() + ").");
        }
        return Enum.valueOf((Class<Enum>) destinationClass, ((Enum<?>) source).name());
    } else {
        return mapper.map(source, destinationClass);
    }
}