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:au.com.jwatmuff.eventmanager.util.EnumConvertingWrapDynaBean.java

@SuppressWarnings("unchecked")
@Override/*from  www  .  ja v  a  2s.  c o m*/
public void set(String name, Object value) {
    Class clazz = getDynaProperty(name).getType();
    if ((clazz != null) && clazz.isEnum() && (value instanceof String)) {
        try {
            value = Enum.valueOf(clazz, (String) value);
        } catch (Exception e) {
            value = null;
        }
    }
    super.set(name, value);
}

From source file:org.openmrs.calculation.CalculationUtil.java

/**
 * Utility method that casts the specified value to the specified Type and handles conversions
 * to primitive wrapper classes in a better/more lenient way than java's type casting. Note that
 * the method will throw a {@link ConversionException} at runtime if it fails to convert the
 * specified value//from   w  w  w.  j a  v  a  2 s  .co  m
 * 
 * @see ConversionException
 * @param valueToCast the value to be cast
 * @param clazz the class to cast to
 * @return a value of the specified type
 * @should fail if the value to convert is not of a compatible type
 * @should convert the value to the specified type if it is compatible
 * @should return null if the passed in value is null
 * @should convert a valid string value to Boolean
 * @should convert a character value to Character
 * @should convert a valid string value to Short
 * @should convert a valid string value to Integer
 * @should convert a valid string value to Long
 * @should convert a valid string value to Float
 * @should convert a valid string value to Double
 * @should convert a valid string value to Byte
 * @should convert a single character value to Short
 * @should convert a valid single character value to Integer
 * @should convert a valid single character value to Long
 * @should convert a result with an number value in the valid range to byte
 * @should convert a valid string to an enum constant
 * @should convert a valid string to a class object
 * @should convert a valid string to a Locale
 * @should format a date object to a string using the default date format
 */
@SuppressWarnings("unchecked")
public static <T> T cast(Object value, Class<T> clazz) {
    if (value == null)
        return null;

    if (clazz == null)
        throw new IllegalArgumentException("The class to cast to cannot be null");

    T castValue = null;
    // We should be able to convert any value to a String      
    if (String.class.isAssignableFrom(clazz)) {
        if (Date.class.isAssignableFrom(value.getClass()))
            castValue = (T) Context.getDateFormat().format((Date) value);
        else
            castValue = (T) value.toString();
    } else {
        //we should be able to convert strings to simple types like String "2" to integer 2, 
        //enums, dates, etc. Java types casting doesn't allow this so we need to transform the value first to
        //a string. BeanUtils from old spring versions doesn't consider enums as simple types
        if (BeanUtils.isSimpleValueType(clazz) || clazz.isEnum()) {
            try {
                String stringValue = null;
                //objects of types like date and Class whose toString methods are not reliable
                if (String.class.isAssignableFrom(value.getClass()))
                    stringValue = (String) value;
                else
                    stringValue = value.toString();

                if (Character.class.equals(clazz) && stringValue.length() == 1) {
                    value = stringValue.charAt(0);
                } else if (Locale.class.isAssignableFrom(clazz)) {
                    return (T) LocaleUtility.fromSpecification(stringValue);
                } else if (Class.class.isAssignableFrom(clazz)) {
                    return (T) Context.loadClass(stringValue);
                } else {
                    Method method = clazz.getMethod("valueOf", new Class<?>[] { String.class });
                    value = method.invoke(null, stringValue);
                }
            } catch (Exception e) {
                //ignore and default to clazz.cast below
            }
        }

        try {
            castValue = clazz.cast(value);
        } catch (ClassCastException e) {
            throw new ConversionException(value, clazz);
        }
    }

    return castValue;
}

From source file:org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.resolver.EnumeratedResolver.java

private boolean isEnum(Class<?> fc) {
    if (fc != null) {
        return fc.isEnum();
    }//from ww w . jav  a  2s . c  om
    return false;
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

public final static String fieldTypefromClass(Class<?> cls) {
    Objects.requireNonNull(cls);/*from www  .j  a v a2s.  c om*/

    // by default return TEXT
    String result = "text";
    if (cls.equals(Boolean.class) || cls.equals(boolean.class)) {
        result = "checkbox";
    } else if (Number.class.isAssignableFrom(cls)) {
        result = "number";
    } else if (cls.isEnum()) {
        result = "select";
    }

    return result;
}

From source file:org.rapidoid.util.RapidoidThingsTest.java

@Test
public void classesShouldExtendRapidoidThing() {
    for (String cls : Cls.getRapidoidClasses()) {
        Class<?> clazz = Cls.get(cls);

        if (!clazz.isInterface() && !clazz.isEnum() && !clazz.isAnnotation()) {
            U.must(RapidoidThing.class.isAssignableFrom(clazz) || clazz == TestCommons.class
                    || cls.startsWith("org.rapidoid.fluent.") || cls.startsWith("org.rapidoid.benchmark.")
                    || Exception.class.isAssignableFrom(clazz) || ClassLoader.class.isAssignableFrom(clazz)
                    || HibernatePersistenceProvider.class.isAssignableFrom(clazz)
                    || OutputStream.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)
                    || AbstractMojo.class.isAssignableFrom(clazz)
                    || EmbeddedMavenCli.class.isAssignableFrom(clazz)
                    || JsonSerializer.class.isAssignableFrom(clazz)
                    || JsonDeserializer.class.isAssignableFrom(clazz)
                    || LogFactory.class.isAssignableFrom(clazz) || Thread.class.isAssignableFrom(clazz),
                    "" + cls);
        }//from www. ja  v  a 2  s . c o m
    }
}

From source file:com.astamuse.asta4d.web.initialization.SimplePropertyFileInitializer.java

protected BeanUtilsBean retrieveBeanUtilsBean() {
    BeanUtilsBean bu = new BeanUtilsBean(new ConvertUtilsBean() {

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override/*from  www .  j  av  a 2s .co m*/
        public Object convert(String value, Class clazz) {
            if (clazz.isEnum()) {
                return Enum.valueOf(clazz, value);
            } else if (clazz.equals(Class.class)) {
                try {
                    return Class.forName(value);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else if (expectInstance(clazz)) {
                try {
                    return Class.forName(value).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                return super.convert(value, clazz);
            }
        }

    });
    return bu;
}

From source file:ca.oson.json.util.ObjectUtil.java

public static boolean isBasicDataType(Class valueType) {
    if (valueType == null) { // no idea, just assume
        return true;
    }/* ww w  . ja  v  a2  s .  c  o m*/

    if (valueType.isPrimitive() || valueType.isEnum()) {
        return true;
    }

    if (Number.class.isAssignableFrom(valueType) || Date.class.isAssignableFrom(valueType)) {
        return true;
    }

    if (valueType == String.class || valueType == Character.class || valueType == Boolean.class) {
        return true;
    }

    return false;
}

From source file:com.opengamma.masterdb.security.SecurityTestCase.java

protected static <T> List<T> getTestObjects(final Class<T> clazz, final Class<?> parent) {
    final List<T> objects = new ArrayList<T>();
    if (clazz.isEnum()) {
        for (final T value : clazz.getEnumConstants()) {
            objects.add(value);//from  ww w  .j a  v a 2 s.c  o m
        }
    } else {
        final Object key;
        if (Collection.class.equals(clazz)) {
            key = Pair.of(parent, clazz);
        } else if (List.class.equals(clazz)) {
            key = Pair.of(parent, clazz);
        } else {
            key = clazz;
        }
        final TestDataProvider<T> provider = (TestDataProvider<T>) s_dataProviders.get(key);
        if (provider == null) {
            throw new IllegalArgumentException("No random provider for " + clazz);
        }
        provider.getValues(objects);
    }
    Collections.shuffle(objects);
    return objects;
}

From source file:org.thelq.stackexchange.api.model.types.EntryFormatTest.java

@DataProvider
public Object[][] enumsInFieldsAreNotFromAnotherClassDataProvider() throws IOException {
    return TestUtils.toTestParameters(getEntriesFields(new Predicate<Field>() {
        public boolean apply(Field input) {
            Class type = input.getType();
            return type.isEnum() && type.getDeclaringClass() != null;
        }//from  ww w  . j  a v  a  2 s.c o m
    }));
}

From source file:org.openspaces.rest.utils.ControllerUtils.java

public static Object convertPropertyToPrimitiveType(String object, Class type, String propKey) {
    if (type.equals(Long.class) || type.equals(Long.TYPE))
        return Long.valueOf(object);

    if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
        return Boolean.valueOf(object);

    if (type.equals(Integer.class) || type.equals(Integer.TYPE))
        return Integer.valueOf(object);

    if (type.equals(Byte.class) || type.equals(Byte.TYPE))
        return Byte.valueOf(object);

    if (type.equals(Short.class) || type.equals(Short.TYPE))
        return Short.valueOf(object);

    if (type.equals(Float.class) || type.equals(Float.TYPE))
        return Float.valueOf(object);

    if (type.equals(Double.class) || type.equals(Double.TYPE))
        return Double.valueOf(object);

    if (type.isEnum())
        return Enum.valueOf(type, object);

    if (type.equals(String.class) || type.equals(Object.class))
        return String.valueOf(object);

    if (type.equals(java.util.Date.class)) {
        try {/*  ww w .  j a v a2 s .  c o  m*/
            return simpleDateFormat.parse(object);
        } catch (ParseException e) {
            throw new RestException(
                    "Unable to parse date [" + object + "]. Make sure it matches the format: " + date_format);
        }
    }

    //unknown type
    throw new UnsupportedTypeException("Non primitive type when converting property [" + propKey + "]:" + type);
}