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.guzz.builder.JPA2AnnotationsBuilder.java

protected static void addPropertyMapping(GuzzContextImpl gf, POJOBasedObjectMapping map, SimpleTable st,
        String name, AnnotatedElement element, Class dataType) {
    javax.persistence.Column pc = element.getAnnotation(javax.persistence.Column.class);
    javax.persistence.Basic pb = element.getAnnotation(javax.persistence.Basic.class);
    javax.persistence.Enumerated pe = element.getAnnotation(javax.persistence.Enumerated.class);
    org.guzz.annotations.Column gc = element.getAnnotation(org.guzz.annotations.Column.class);

    String type = gc == null ? null : gc.type();
    String nullValue = gc == null ? null : gc.nullValue();
    String column = pc == null ? null : pc.name();
    boolean lazy = pb == null ? false : pb.fetch() == FetchType.LAZY;
    Class loader = gc == null ? null : gc.loader();

    if (dataType.isEnum()) {
        EnumType etype = EnumType.ORDINAL;

        if (pe != null) {
            etype = pe.value();//from  ww w  . j  a va 2  s. c o  m
        }

        if (etype == EnumType.ORDINAL) {
            type = "enum.ordinal|" + dataType.getName();
        } else {
            type = "enum.string|" + dataType.getName();
        }
    }

    boolean insertIt = pc == null ? true : pc.insertable();
    boolean updateIt = pc == null ? true : pc.updatable();

    if (StringUtil.isEmpty(column)) {
        column = name;
    }

    TableColumn col = st.getColumnByPropName(name);
    if (col != null) {
        log.warn("field/property [" + name + "] already exsits in the parent class of [" + st.getBusinessName()
                + "]. Ignore it.");

        return;
    }

    if (loader == null || NullValue.class.isAssignableFrom(loader)) {
        loader = null;
    }

    try {
        col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type,
                loader == null ? null : loader.getName());
        col.setNullValue(nullValue);
        col.setAllowInsert(insertIt);
        col.setAllowUpdate(updateIt);
        col.setLazy(lazy);

        st.addColumn(col);
    } catch (DataTypeException dte) {
        //???JPA??Map, Set
        if (log.isDebugEnabled()) {
            log.debug("Unsupported data type is found in annotation, property is:[" + name + "], business is:["
                    + st.getBusinessName() + "]. Ignore this property.", dte);
        } else {
            log.warn("Ignore unsupported data type in annotation, property is:[" + name + "], business is:["
                    + st.getBusinessName() + "], msg is:" + dte.getMessage());
        }
    }
}

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override/* w  w w.  j a v  a  2s .c  om*/
public <T> String convertToString(final Class<T> type, final T instance, final Locale locale)
        throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    String result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug(
                "Converting to string with type {} with locale {} and value: {}", type, locale, instance);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        final Enum<?> enumInstance = enumType.cast(instance);
        if (!CheckUtil.isNull(enumInstance)) {
            result = enumInstance.name();
        }
    } else {
        result = this.converterTool.convertToString(type, instance, locale);
    }
    return result;
}

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override//from w  ww  .  j  av  a2s .c om
public <T> String convertToString(final Class<T> type, final T instance, final String format)
        throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    String result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug(
                "Converting to string with type {} with format {} and value: {}", type, format, instance);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        final Enum<?> enumInstance = enumType.cast(instance);
        if (!CheckUtil.isNull(enumInstance)) {
            result = enumInstance.name();
        }
    } else {
        result = this.converterTool.convertToString(type, instance, format);
    }
    return result;
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

public static boolean canBeFunctionalMocked(Type type) {

    Class<?> rawClass = new GenericClass(type).getRawClass();
    final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

    if (Properties.hasTargetClassBeenLoaded() && (rawClass.equals(targetClass))) {
        return false;
    }/*from   w  w  w .  j  a va  2s .  c  om*/

    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName())
            || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive()
            || rawClass.isAnonymousClass() || rawClass.isEnum() ||
            //note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
            !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }

    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
        if a class has not been instrumented (eg because belonging to javax.*),
        then if it is final we cannot mock it :(
        recall that instrumentation does remove the final modifiers
         */
        return false;
    }

    //FIXME: tmp fix to avoid mocking any class with package access methods
    try {
        for (Method m : rawClass.getDeclaredMethods()) {

            /*
            Unfortunately, it does not seem there is a "isPackageLevel" method, so we have
            to go by exclusion
             */

            if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())
                    && !Modifier.isPrivate(m.getModifiers()) && !m.isBridge() && !m.isSynthetic()
                    && !m.getName().equals(ClassResetter.STATIC_RESET)) {
                return false;
            }
        }
    } catch (NoClassDefFoundError | Exception e) {
        //this could happen if we failed to load the class
        AtMostOnceLogger.warn(logger,
                "Failed to check if can mock class " + rawClass.getName() + ": " + e.getMessage());
        return false;
    }

    //avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }

    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        //avoid weird cases like java.lang.Appendable
        return false;
    }

    //ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList(
    //add here if needed
    );

    if (avoid.contains(rawClass)) {
        return false;
    }

    return true;
}

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override/* ww  w.  jav  a2s . c o  m*/
public <T> T convertToInstance(final Class<T> type, final String stringValue, final Locale locale)
        throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    T result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug("Converting to instance type {} with locale {} and value: {}",
                type, locale, stringValue);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        if (!StringUtil.isEmptyString(stringValue)) {
            result = (T) Enum.valueOf(enumType, stringValue);
        }
    } else {
        result = this.converterTool.convertToInstance(type, stringValue, locale);
    }
    return result;
}

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override/*from  ww w.j  av a  2  s.c o m*/
public <T> T convertToInstance(final Class<T> type, final String stringValue, final String format)
        throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    T result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug("Converting to instance type {} with format {} and value: {}",
                type, stringValue);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        if (!StringUtil.isEmptyString(stringValue)) {
            result = (T) Enum.valueOf(enumType, stringValue);
        }
    } else {
        result = this.converterTool.convertToInstance(type, stringValue, format);
    }
    return result;
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * Convenience method to get the normalizer (see {@link #safetypes}) for the given class.
 * /*from w w  w  .  j  av a2s.  c o m*/
 * @param c class to normalize
 * @return the {@link Normalizer} to use
 * @see #getNormalizer(String)
 */
public static Normalizer getNormalizer(Class c) {
    String simpleClassName = c.getSimpleName().toLowerCase();
    if (c.isEnum()) {
        simpleClassName = "enum";
    }
    return getNormalizer(simpleClassName);
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T parse(Class<T> type, String stringValue) throws IllegalArgumentException {
    if (type.equals(String.class)) {
        return (T) stringValue;
    }// w  w  w .  j a va 2  s.co  m

    if (type.equals(Boolean.class) || type.equals(boolean.class)) {
        return (T) Boolean.valueOf(stringValue);
    }
    try {
        if (type.equals(Integer.class) || type.equals(int.class)) {
            return (T) Integer.valueOf(stringValue);
        }
        if (type.equals(Long.class) || type.equals(long.class)) {
            return (T) Long.valueOf(stringValue);
        }
        if (type.equals(Short.class) || type.equals(short.class)) {
            return (T) Short.valueOf(stringValue);
        }
        if (type.equals(Byte.class) || type.equals(byte.class)) {
            return (T) Byte.valueOf(stringValue);
        }
        if (type.equals(Double.class) || type.equals(double.class)) {
            return (T) Double.valueOf(stringValue);
        }
        if (type.equals(Float.class) || type.equals(float.class)) {
            return (T) Float.valueOf(stringValue);
        }
        if (type.equals(File.class)) {
            return (T) new File(stringValue);
        }
    } catch (final NumberFormatException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    if (type.isEnum()) {
        @SuppressWarnings("rawtypes")
        final Class enumType = type;
        return (T) Enum.valueOf(enumType, stringValue);
    }
    throw new IllegalArgumentException("Can't handle type " + type);

}

From source file:org.jtester.module.utils.ObjectFormatter.java

/**
 * Actual implementation of the formatting.
 *
 * @param object       The instance/*w w w. ja  v  a  2  s .co  m*/
 * @param currentDepth The current recursion depth
 * @param result       The builder to append the result to, not null
 */
protected void formatImpl(Object object, int currentDepth, StringBuilder result) {
    // get the actual value if the value is wrapped by a Hibernate proxy
    object = getUnproxiedValue(object);

    if (object == null) {
        result.append(String.valueOf(object));
        return;
    }
    if (object instanceof String) {
        result.append('"');
        result.append(object);
        result.append('"');
        return;
    }
    if (object instanceof Number || object instanceof Date) {
        result.append(String.valueOf(object));
        return;
    }
    if (object instanceof Character) {
        result.append('\'');
        result.append(String.valueOf(object));
        result.append('\'');
        return;
    }
    Class<?> dummyObjectClass = getDummyObjectClass();
    if (dummyObjectClass != null && dummyObjectClass.isAssignableFrom(object.getClass())) {
        result.append("Dummy<");
        result.append(object.toString());
        result.append(">");
        return;
    }
    Class<?> type = object.getClass();
    if (type.isPrimitive() || type.isEnum()) {
        result.append(String.valueOf(object));
        return;
    }
    if (formatMock(object, result)) {
        return;
    }
    if (formatProxy(object, result)) {
        return;
    }
    if (type.getName().startsWith("java.lang")) {
        result.append(String.valueOf(object));
        return;
    }
    if (type.isArray()) {
        formatArray(object, currentDepth, result);
        return;
    }
    if (object instanceof Collection) {
        formatCollection((Collection<?>) object, currentDepth, result);
        return;
    }
    if (object instanceof Map) {
        formatMap((Map<?, ?>) object, currentDepth, result);
        return;
    }
    if (currentDepth >= maxDepth) {
        result.append(getShortClassName(type));
        result.append("<...>");
        return;
    }
    formatObject(object, currentDepth, result);
}