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.evosuite.executionmode.ListParameters.java

public static Object execute() {

    List<Row> rows = new ArrayList<Row>();

    /*//from  w  w w  . j av a2  s. c o  m
     * This is necessary, as reading from evosuite-files properties
     * can change the defaults
     */
    Properties.getInstance().resetToDefaults();

    for (Field f : Properties.class.getFields()) {
        if (f.isAnnotationPresent(Parameter.class)) {
            Parameter p = f.getAnnotation(Parameter.class);

            String description = p.description();
            Class<?> type = f.getType();

            if (type.isEnum()) {
                description += " (Values: " + Arrays.toString(type.getEnumConstants()) + ")";
            }

            String def;
            try {
                Object obj = f.get(null);
                if (obj == null) {
                    def = "";
                } else {
                    if (type.isArray()) {
                        def = Arrays.toString((Object[]) obj);
                    } else {
                        def = obj.toString();
                    }
                }
            } catch (Exception e) {
                def = "";
            }

            rows.add(new Row(p.key(), type.getSimpleName(), description, def));
        }
    }

    Collections.sort(rows);

    String name = "Name";
    String type = "Type";
    String defaultValue = "Default";
    String description = "Description";
    String space = "   ";

    int maxName = Math.max(name.length(), getMaxNameLength(rows));
    int maxType = Math.max(type.length(), getMaxTypeLength(rows));
    int maxDefault = Math.max(defaultValue.length(), getMaxDefaultLength(rows));

    LoggingUtils.getEvoLogger().info(name + getGap(name, maxName) + space + type + getGap(type, maxType) + space
            + defaultValue + getGap(defaultValue, maxDefault) + space + description);

    for (Row row : rows) {
        LoggingUtils.getEvoLogger()
                .info(row.name + getGap(row.name, maxName) + space + row.type + getGap(row.type, maxType)
                        + space + row.defaultValue + getGap(row.defaultValue, maxDefault) + space
                        + row.description);
    }

    return null;
}

From source file:kelly.util.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 www  .j a v  a 2 s  . com*/
 * @param clazz the type to check
 * @return whether the given type represents a "simple" value type
 */
public static boolean isSimpleValueType(Class<?> clazz) {
    return 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.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

@SuppressWarnings("unchecked")
private static void setMultiplicityAndDataType(EPackage vvEPackage, EAttribute att, Type type) {
    if (type instanceof ParameterizedType) {
        setMultiplicityAndDataType(vvEPackage, att, ((ParameterizedType) type).getActualTypeArguments()[0]);
    } else if (type instanceof GenericArrayType) {
        setMultiplicityAndDataType(vvEPackage, att, ((GenericArrayType) type).getGenericComponentType());
    } else if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz.isEnum()) {
            att.setEType(getEEnum(vvEPackage, (Class<? extends Enum<?>>) clazz));
        } else {//from   w  w w. j a  va  2 s.c  o  m
            att.setEType(getEDataType(vvEPackage, clazz));
        }
    }
}

From source file:org.localmatters.serializer.util.ReflectionUtils.java

/**
 * Returns whether the instances of the given class can be represent by a
 * simple, non-numeric value; i.e whether this string, a date, an
 * enumeration, etc./*from w ww.  j  a  v a2s  .  c om*/
 * @param klass
 * @return True is the class is non-numeric and simple, false otherwise
 */
public static boolean isNonNumericSimple(Class<?> klass) {
    return String.class.equals(klass) || Date.class.isAssignableFrom(klass) || klass.isEnum()
            || Locale.class.isAssignableFrom(klass);
}

From source file:Main.java

/**
 * Checks if the given class can be wrapped directly
 * @param clazz The given class//  ww  w  . j  a v  a 2s.  c o  m
 * @return true if the given class is an autoboxed class e.g., Integer
 */
private static boolean isWrapperType(Class clazz) {
    return WRAPPER_TYPES.contains(clazz) || clazz.isPrimitive() || clazz.isEnum();
}

From source file:eu.crisis_economics.utilities.EnumDistribution.java

public static <T extends Enum<T>> EnumDistribution<T> // Immutable
        create(Class<T> token, String sourceFile) throws IOException {
    if (token == null)
        throw new NullArgumentException();
    if (!token.isEnum())
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is not an enum.");
    if (token.getEnumConstants().length == 0)
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is an empty enum.");
    EnumDistribution<T> result = new EnumDistribution<T>();
    result.values = token.getEnumConstants();
    result.probabilities = new EnumMap<T, Double>(token);
    Map<String, T> converter = new HashMap<String, T>();
    final int numberOfValues = result.values.length;
    int[] valueIndices = new int[numberOfValues];
    double[] valueProbabilities = new double[numberOfValues];
    BitSet valueIsComitted = new BitSet(numberOfValues);
    {// w  ww  . ja  va 2  s.com
        int counter = 0;
        for (T value : result.values) {
            valueIndices[counter] = counter++;
            result.probabilities.put(value, 0.);
            converter.put(value.name(), value);
        }
    }
    BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
    try {
        String newLine;
        while ((newLine = reader.readLine()) != null) {
            if (newLine.isEmpty())
                continue;
            StringTokenizer tokenizer = new StringTokenizer(newLine);
            final String name = tokenizer.nextToken(" ,:\t"), pStr = tokenizer.nextToken(" ,:\t");
            if (tokenizer.hasMoreTokens())
                throw new ParseException(
                        "EnumDistribution: " + newLine + " is not a valid entry in " + sourceFile + ".", 0);
            final double p = Double.parseDouble(pStr);
            if (p < 0. || p > 1.)
                throw new IOException(pStr + " is not a valid probability for the value " + name);
            result.probabilities.put(converter.get(name), p);
            final int ordinal = converter.get(name).ordinal();
            if (valueIsComitted.get(ordinal))
                throw new ParseException("The value " + name + " appears twice in " + sourceFile, 0);
            valueProbabilities[converter.get(name).ordinal()] = p;
            valueIsComitted.set(ordinal, true);
        }
        { // Check sum of probabilities
            double sum = 0.;
            for (double p : valueProbabilities)
                sum += p;
            if (Math.abs(sum - 1.) > 1e2 * Math.ulp(1.))
                throw new IllegalStateException("EnumDistribution: parser has succeeded, but the resulting "
                        + "probaility sum (value " + sum + ") is not equal to 1.");
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        reader.close();
    }
    result.dice = new EnumeratedIntegerDistribution(valueIndices, valueProbabilities);
    return result;
}

From source file:com.trenako.values.LocalizedEnum.java

/**
 * Builds the list with the provided {@code enum} values.
 *
 * @param enumType      the {@code enum} type
 * @param messageSource the {@code MessageSource} to localize the text strings
 * @param failback      the failback interface to produce default messages
 * @return the values list//from   www  .  j a va2 s  . com
 */
public static <T extends Enum<T>, F extends MessageFailback<T>> Iterable<LocalizedEnum<T>> list(
        Class<T> enumType, MessageSource messageSource, F failback) {

    if (!enumType.isEnum()) {
        throw new IllegalArgumentException("The provided type is not an enum");
    }

    T[] consts = enumType.getEnumConstants();
    List<LocalizedEnum<T>> items = new ArrayList<LocalizedEnum<T>>(consts.length);

    for (T val : consts) {
        items.add(new LocalizedEnum<T>(val, messageSource, failback));
    }

    return Collections.unmodifiableList(items);
}

From source file:gr.abiss.calipso.tiers.specifications.GenericSpecifications.java

/**
 * Get an appropriate predicate factory for the given field class
 * @param field//from w  w  w  . ja  va 2s  .  c o m
 * @return
 */
private static IPredicateFactory<?> getPredicateFactoryForClass(Field field) {
    Class clazz = field.getType();
    if (clazz.isEnum()) {
        return new EnumStringPredicateFactory(clazz);
    } else if (Persistable.class.isAssignableFrom(clazz)) {
        if (field.isAnnotationPresent(CurrentPrincipal.class)) {
            return currentPrincipalPredicateFactory;
        } else {
            return anyToOnePredicateFactory;
        }
    } else {
        return factoryForClassMap.get(clazz);
    }
}

From source file:org.unitils.mock.core.proxy.CloneUtil.java

/**
 * @param instanceToClone The instance, not null
 * @return True if the instance is immutable, e.g. a primitive
 *///w w w .  j a  v  a 2s  . c o  m
protected static boolean isImmutable(Object instanceToClone) {
    Class<?> clazz = instanceToClone.getClass();

    if (clazz.isPrimitive() || clazz.isEnum() || clazz.isAnnotation()) {
        return true;
    }
    if (instanceToClone instanceof Number || instanceToClone instanceof String
            || instanceToClone instanceof Character || instanceToClone instanceof Boolean) {
        return true;
    }
    if (clazz.getName().startsWith("com.google.common.collect") && clazz.getName().contains("Immutable")) {
        return true;
    }

    return false;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.IdentityEnumType.java

@SuppressWarnings("unchecked")
public static boolean supports(@SuppressWarnings("rawtypes") Class enumClass) {
    if (!isEnabled())
        return false;
    if (enumClass.isEnum()) {
        try {//w  ww  .  j a v  a2 s .c  om
            Method idAccessor = enumClass.getMethod(ENUM_ID_ACCESSOR);
            int mods = idAccessor.getModifiers();
            if (Modifier.isPublic(mods) && !Modifier.isStatic(mods)) {
                Class<?> returnType = idAccessor.getReturnType();
                return returnType != null
                        && typeResolver.basic(returnType.getName()) instanceof AbstractStandardBasicType;
            }
        } catch (NoSuchMethodException e) {
            // ignore
        }
    }
    return false;
}