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.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

private static ObjectNode buildChoicesNode(final ObjectMapper objectMapper, final Type heapValueType,
        final SchemaLoader schemaLoader) {

    if (heapValueType == null || !(heapValueType instanceof Class<?>)) {
        return null;
    }//from   ww w.j  av  a2 s  .c  o  m

    final Class<?> choicesEnumClass = (Class<?>) heapValueType;

    if (!choicesEnumClass.isEnum()) {
        return null;
    }

    final URI choicesUri = schemaLoader.getTypeUri(choicesEnumClass);
    final String choicesName = choicesEnumClass.getSimpleName();
    final ObjectNode choicesNode = objectMapper.createObjectNode();

    choicesNode.put(PropertyName.title.name(), choicesName);
    choicesNode.put(PropertyName.uri.name(), choicesUri.toString());

    // TODO: Only embed the choices once per schema to lighten the download?
    final Object[] enumConstants = choicesEnumClass.getEnumConstants();
    if (enumConstants != null && enumConstants.length > 0) {
        final ArrayNode valuesNode = objectMapper.createArrayNode();

        choicesNode.put(PropertyName.values.name(), valuesNode);

        for (final Object enumConstant : enumConstants) {
            final String choice = String.valueOf(enumConstant);
            valuesNode.add(choice);
        }
    }

    return choicesNode;
}

From source file:com.github.dozermapper.core.util.MappingUtils.java

/**
 * Used to test if {@code srcFieldClass} is enum.
 *
 * @param srcFieldClass the source field to be tested.
 * @return {@code true} if and only if current running JRE is 1.5 or above, and
 * {@code srcFieldClass} is enum; otherwise return {@code false}.
 *///  w ww.j  a v  a 2 s  . c om
public static boolean isEnumType(Class<?> srcFieldClass) {
    if (srcFieldClass.isAnonymousClass()) {
        //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class.
        //This is used to ensure Dozer can get correct Enum type.
        srcFieldClass = srcFieldClass.getEnclosingClass();
    }
    return srcFieldClass.isEnum();
}

From source file:org.springframework.flex.core.io.SpringPropertyProxy.java

/**
 * Factory method for creating correctly configured Spring property proxy instances.
 * @param beanType the type being introspected
 * @param useDirectFieldAccess whether to access fields directly
 * @param conversionService the conversion service to use for property type conversion
 * @return a properly configured property proxy
 *///w w w. j  a v a 2  s .c  o  m
public static SpringPropertyProxy proxyFor(Class<?> beanType, boolean useDirectFieldAccess,
        ConversionService conversionService) {
    if (PropertyProxyUtils.hasAmfCreator(beanType)) {
        SpringPropertyProxy proxy = new DelayedWriteSpringPropertyProxy(beanType, useDirectFieldAccess,
                conversionService);
        return proxy;
    } else {
        Assert.isTrue(beanType.isEnum() || ClassUtils.hasConstructor(beanType),
                "Failed to create SpringPropertyProxy for " + beanType.getName() + " - Classes mapped "
                        + "for deserialization from AMF must have either a no-arg default constructor, "
                        + "or a constructor annotated with " + AmfCreator.class.getName());
        SpringPropertyProxy proxy = new SpringPropertyProxy(beanType, useDirectFieldAccess, conversionService);

        try {
            //If possible, create an instance to introspect and cache the property names               
            Object instance = BeanUtils.instantiate(beanType);
            proxy.setPropertyNames(
                    PropertyProxyUtils.findPropertyNames(conversionService, useDirectFieldAccess, instance));
        } catch (BeanInstantiationException ex) {
            //Property names can't be cached, but this is ok
        }

        return proxy;
    }
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

public static final boolean canConstructTarget(Class _class) {
    boolean isFinal = Modifier.isFinal(_class.getModifiers());
    boolean isArray = _class.isArray();
    boolean isEnum = _class.isEnum();

    return (isFinal == false && isArray == false && isEnum == false);
}

From source file:com.htmlhifive.pitalium.core.config.PtlTestConfig.java

/**
 * ?????????/*from  w  ww  .j  a  v  a2s.c o m*/
 * 
 * @param type ??String, int(Integer), double(Double),Enum?????
 * @param value ??
 * @return ??
 * @throws IllegalArgumentException Enum???????
 * @throws TestRuntimeException ??????????
 */
static Object convertFromString(Class<?> type, String value)
        throws IllegalArgumentException, TestRuntimeException {
    if (type == String.class) {
        return value;
    } else if (type == int.class || type == Integer.class) {
        return Integer.parseInt(value);
    } else if (type == double.class || type == Double.class) {
        return Double.parseDouble(value);
    } else if (type.isEnum()) {
        for (Object o : type.getEnumConstants()) {
            if (((Enum) o).name().equals(value)) {
                return o;
            }
        }
        throw new IllegalArgumentException();
    } else {
        throw new TestRuntimeException("Cannot convert type \"" + type.getName() + "\"");
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

@SuppressWarnings("rawtypes")
public static boolean isSirenProperty(Class<?> type, Object obj, Field field) {
    boolean isProp = false;

    Siren4JProperty anno = field.getAnnotation(Siren4JProperty.class);
    if (anno != null || type.isEnum()) {
        isProp = true;/*from   w  w  w .j a va  2 s. c om*/
    } else if (ArrayUtils.contains(propertyTypes, type)) {
        isProp = true;
    } else if (obj != null && Collection.class.isAssignableFrom(type)) {
        //Try to determine value type
        if (!((Collection) obj).isEmpty()) {
            Object first = findFirstNonNull(((Collection) obj).iterator());
            if (first == null || ArrayUtils.contains(propertyTypes, first.getClass())) {
                isProp = true;
            }
        }
    } else if (obj != null && Map.class.isAssignableFrom(type)) {
        //Try to determine value types of key and value
        if (!((Map) obj).isEmpty()) {
            Object firstKey = findFirstNonNull(((Map) obj).keySet().iterator());
            Object firstVal = findFirstNonNull(((Map) obj).entrySet().iterator());
            if ((firstKey == null || ArrayUtils.contains(propertyTypes, firstKey.getClass()))
                    && (firstVal == null || ArrayUtils.contains(propertyTypes,
                            ((HashMap.Entry) firstVal).getValue().getClass()))) {
                isProp = true;
            }
        }
    }
    return isProp;
}

From source file:com.turbospaces.model.BO.java

/**
 * register the set of persistent classes and enrich kryo with some extract serialized related to persistent class.
 * //from   w  w  w  . j ava  2  s .  c  om
 * @param kryo
 *            serialization provider
 * @param persistentEntities
 *            classes to register
 * @throws ClassNotFoundException
 *             re-throw conversion service
 * @throws NoSuchMethodException
 *             re-throw cglib's exception
 * @throws SecurityException
 *             re-throw cglib's exception
 * @throws IntrospectionException
 *             re-throw introspection exception
 */
public static void registerPersistentClasses(final DecoratedKryo kryo,
        final BasicPersistentEntity... persistentEntities)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IntrospectionException {
    for (BasicPersistentEntity<?, ?> e : persistentEntities) {
        BO bo = new BO(e);
        bo.getOriginalPersistentEntity().doWithProperties(new PropertyHandler() {
            @Override
            public void doWithPersistentProperty(final PersistentProperty p) {
                Class type = p.getType();
                if (type.isArray() && !kryo.isTypeRegistered(type)) {
                    SingleDimensionArraySerializer serializer = new SingleDimensionArraySerializer(type, kryo);
                    kryo.register(type, serializer);
                } else if (type.isEnum() && !kryo.isTypeRegistered(type)) {
                    EnumSerializer enumSerializer = new EnumSerializer(type);
                    kryo.register(type, enumSerializer);
                }
            }
        });
        Class<?> arrayWrapperType = Class.forName("[L" + e.getType().getName() + ";");
        PropertiesSerializer serializer = new PropertiesSerializer(kryo, bo);
        SingleDimensionArraySerializer arraysSerializer = new SingleDimensionArraySerializer(arrayWrapperType,
                kryo);
        kryo.register(e.getType(), serializer);
        kryo.register(arrayWrapperType, arraysSerializer);
    }
}

From source file:com.evolveum.midpoint.prism.util.CloneUtil.java

public static <T> T clone(T orig) {
    if (orig == null) {
        return null;
    }//  ww w  . j a  va 2  s.  co m
    Class<? extends Object> origClass = orig.getClass();
    if (ClassUtils.isPrimitiveOrWrapper(origClass)) {
        return orig;
    }
    if (origClass.isArray()) {
        return cloneArray(orig);
    }
    if (orig instanceof PolyString) {
        // PolyString is immutable
        return orig;
    }
    if (orig instanceof String) {
        // ...and so is String
        return orig;
    }
    if (orig instanceof QName) {
        // the same here
        return orig;
    }
    if (origClass.isEnum()) {
        return orig;
    }
    //        if (orig.getClass().equals(QName.class)) {
    //            QName origQN = (QName) orig;
    //            return (T) new QName(origQN.getNamespaceURI(), origQN.getLocalPart(), origQN.getPrefix());
    //        }
    if (orig instanceof RawType) {
        return (T) ((RawType) orig).clone();
    }
    if (orig instanceof Item<?, ?>) {
        return (T) ((Item<?, ?>) orig).clone();
    }
    if (orig instanceof PrismValue) {
        return (T) ((PrismValue) orig).clone();
    }
    if (orig instanceof ObjectDelta<?>) {
        return (T) ((ObjectDelta<?>) orig).clone();
    }
    if (orig instanceof ObjectDeltaType) {
        return (T) ((ObjectDeltaType) orig).clone();
    }
    if (orig instanceof ItemDelta<?, ?>) {
        return (T) ((ItemDelta<?, ?>) orig).clone();
    }
    if (orig instanceof Definition) {
        return (T) ((Definition) orig).clone();
    }
    /*
     * In some environments we cannot clone XMLGregorianCalendar because of this:
     * Error when cloning class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl, will try serialization instead.
       * java.lang.IllegalAccessException: Class com.evolveum.midpoint.prism.util.CloneUtil can not access a member of
       * class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl with modifiers "public"
     */
    if (orig instanceof XMLGregorianCalendar) {
        return (T) XmlTypeConverter.createXMLGregorianCalendar((XMLGregorianCalendar) orig);
    }
    if (orig instanceof Cloneable) {
        T clone = javaLangClone(orig);
        if (clone != null) {
            return clone;
        }
    }
    if (orig instanceof Serializable) {
        // Brute force
        if (PERFORMANCE_ADVISOR.isDebugEnabled()) {
            PERFORMANCE_ADVISOR.debug("Cloning a Serializable ({}). It could harm performance.",
                    orig.getClass());
        }
        return (T) SerializationUtils.clone((Serializable) orig);
    }
    throw new IllegalArgumentException("Cannot clone " + orig + " (" + origClass + ")");
}

From source file:org.jaffa.qm.util.PropertyFilter.java

private static void getFieldList(Class clazz, List<String> fieldList, String prefix, Deque<Class> classStack)
        throws IntrospectionException {
    //To avoid recursion, bail out if the input Class has already been introspected
    if (classStack.contains(clazz)) {
        if (log.isDebugEnabled())
            log.debug("Fields from " + clazz + " prefixed by " + prefix
                    + " will be ignored, since the class has already been introspected as per the stack "
                    + classStack);/*from ww  w  . ja v a  2 s .c o  m*/
        return;
    } else
        classStack.addFirst(clazz);

    //Introspect the input Class
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    String name = pd.getName();
                    String qualifieldName = prefix == null || prefix.length() == 0 ? name : prefix + '.' + name;
                    Class type = pd.getPropertyType();
                    if (type.isArray())
                        type = type.getComponentType();
                    if (type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)
                            || IDateBase.class.isAssignableFrom(type) || Currency.class.isAssignableFrom(type)
                            || type.isPrimitive() || type.isEnum())
                        fieldList.add(qualifieldName);
                    else
                        getFieldList(type, fieldList, qualifieldName, classStack);
                }
            }
        }
    }

    classStack.removeFirst();
}

From source file:org.apache.pulsar.common.util.FieldParser.java

/**
 * Convert the given object value to the given class.
 *
 * @param from/*from w ww. java 2  s.c  o  m*/
 *            The object value to be converted.
 * @param to
 *            The type class which the given object should be converted to.
 * @return The converted object value.
 * @throws UnsupportedOperationException
 *             If no suitable converter can be found.
 * @throws RuntimeException
 *             If conversion failed somehow. This can be caused by at least an ExceptionInInitializerError,
 *             IllegalAccessException or InvocationTargetException.
 */
@SuppressWarnings("unchecked")
public static <T> T convert(Object from, Class<T> to) {

    checkNotNull(to);
    if (from == null) {
        return null;
    }

    to = (Class<T>) wrap(to);
    // Can we cast? Then just do it.
    if (to.isAssignableFrom(from.getClass())) {
        return to.cast(from);
    }

    // Lookup the suitable converter.
    String converterId = from.getClass().getName() + "_" + to.getName();
    Method converter = CONVERTERS.get(converterId);

    if (to.isEnum()) {
        // Converting string to enum
        EnumResolver r = EnumResolver.constructUsingToString((Class<Enum<?>>) to, null);
        T value = (T) r.findEnum((String) from);
        if (value == null) {
            throw new RuntimeException("Invalid value '" + from + "' for enum " + to);
        }
        return value;
    }

    if (converter == null) {
        throw new UnsupportedOperationException("Cannot convert from " + from.getClass().getName() + " to "
                + to.getName() + ". Requested converter does not exist.");
    }

    // Convert the value.
    try {
        Object val = converter.invoke(to, from);
        return to.cast(val);
    } catch (Exception e) {
        throw new RuntimeException("Cannot convert from " + from.getClass().getName() + " to " + to.getName()
                + ". Conversion failed with " + e.getMessage(), e);
    }
}