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:com.nike.cerberus.cli.CerberusRunner.java

private void printCustomUsage() {
    StringBuilder sb = new StringBuilder("Usage: cerberus [options] [command] [command options]\n");

    String indent = "";
    //indenting/*from www.j ava 2 s .  c  o  m*/
    int descriptionIndent = 6;
    int indentCount = indent.length() + descriptionIndent;

    int longestName = 0;
    List<ParameterDescription> sorted = Lists.newArrayList();
    for (ParameterDescription pd : commander.getParameters()) {
        if (!pd.getParameter().hidden()) {
            sorted.add(pd);
            // + to have an extra space between the name and the description
            int length = pd.getNames().length() + 2;
            if (length > longestName) {
                longestName = length;
            }
        }
    }

    sb.append(indent).append("  Options:\n");

    sorted.stream().sorted((p0, p1) -> p0.getLongestName().compareTo(p1.getLongestName())).forEach(pd -> {
        WrappedParameter parameter = pd.getParameter();
        sb.append(indent).append("  " + (parameter.required() ? "* " : "  ")
                + Chalk.on(pd.getNames()).green().bold().toString() + "\n");
        wrapDescription(sb, indentCount, s(indentCount) + pd.getDescription());
        Object def = pd.getDefault();
        if (def != null) {
            String displayedDef = StringUtils.isBlank(def.toString()) ? "<empty string>" : def.toString();
            sb.append("\n" + s(indentCount))
                    .append("Default: " + Chalk.on(displayedDef).yellow().bold().toString());
        }
        Class<?> type = pd.getParameterized().getType();
        if (type.isEnum()) {
            String values = EnumSet.allOf((Class<? extends Enum>) type).toString();
            sb.append("\n" + s(indentCount))
                    .append("Possible Values: " + Chalk.on(values).yellow().bold().toString());
        }
        sb.append("\n");
    });

    System.out.println(sb.toString());
    System.out.print("  ");
    printCommands();
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Parses the./*from   w w w  .  j  a v a 2 s. com*/
 *
 * @param <T>   the generic type
 * @param cls   the cls
 * @param value the value
 * @return the t
 * @throws java.text.ParseException the parse exception
 */
@SuppressWarnings("unchecked")
public static <T> T parse(Class<T> cls, String value) throws ParseException {
    if (cls.isEnum()) {
        final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember();

        String val = value;
        final Map<String, String> stringToEnumDict = member.get(cls);
        if (stringToEnumDict != null) {
            final String strEnumName = stringToEnumDict.get(value);
            if (strEnumName != null) {
                val = strEnumName;
            }
        }
        for (T o : cls.getEnumConstants()) {
            if (o.toString().equals(val)) {
                return o;
            }
        }
        return null;
    } else if (Number.class.isAssignableFrom(cls)) {
        if (Double.class.isAssignableFrom(cls)) {
            return (T) ((Double) Double.parseDouble(value));
        } else if (Integer.class.isAssignableFrom(cls)) {
            return (T) ((Integer) Integer.parseInt(value));
        } else if (Long.class.isAssignableFrom(cls)) {
            return (T) ((Long) Long.parseLong(value));
        } else if (Float.class.isAssignableFrom(cls)) {
            return (T) ((Float) Float.parseFloat(value));
        } else if (Byte.class.isAssignableFrom(cls)) {
            return (T) ((Byte) Byte.parseByte(value));
        } else if (Short.class.isAssignableFrom(cls)) {
            return (T) ((Short) Short.parseShort(value));
        } else if (BigInteger.class.isAssignableFrom(cls)) {
            return (T) (new BigInteger(value));
        } else if (BigDecimal.class.isAssignableFrom(cls)) {
            return (T) (new BigDecimal(value));
        }
    } else if (Date.class.isAssignableFrom(cls)) {
        DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT);
        return (T) df.parse(value);
    } else if (Boolean.class.isAssignableFrom(cls)) {
        return (T) ((Boolean) Boolean.parseBoolean(value));
    } else if (String.class.isAssignableFrom(cls)) {
        return (T) value;
    }
    return null;
}

From source file:com.quigley.moose.mapping.Mapping.java

public boolean hasTypeHandler(Class<?> clazz) {
    if (clazz.isEnum()) {
        return true;
    }/*from   w  w w  .  j a v  a  2s  . com*/
    if (typeHandlers.containsKey(clazz)) {
        return true;
    } else {
        return false;
    }
}

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

/** @return Classes that should be imported by BCEL during packaging. */
protected Collection<Class<?>> getDependentClasses() {
    ArrayList<Class<?>> dependentClasses = new ArrayList<Class<?>>();
    Class<?> innerType = this.getInnerType();
    if (innerType != null)
        if (innerType.isEnum()) // Enums are not being implicitly picked up...
            dependentClasses.add(innerType);
    return dependentClasses;
}

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

/** @return Classes that should be imported. */
protected Collection<Class<?>> getImportClasses() {
    ArrayList<Class<?>> importClasses = new ArrayList<Class<?>>();
    importClasses.add(this.getAnnotationIOClass());
    Class<?> innerType = this.getInnerType();
    if (innerType != null)
        if (!innerType.isEnum()) // see getType()
            importClasses.add(innerType);
    return importClasses;
}

From source file:com.quigley.moose.mapping.Mapping.java

public TypeHandler getTypeHandler(Class<?> clazz) {
    if (!clazz.isEnum()) {
        if (hasTypeHandler(clazz)) {
            return typeHandlers.get(clazz);
        } else {//from w  w w . ja v a  2  s . c o  m
            throw new MappingException("No type handler for class name '" + clazz.getName() + "'.");
        }

    } else {
        if (!typeHandlers.containsKey(clazz)) {
            TypeHandler typeHandler = new EnumHandler(clazz, mappingNameGenerator);
            typeHandlers.put(clazz, typeHandler);
            return typeHandler;
        }
        return typeHandlers.get(clazz);
    }
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Parses an enum value list.//  w w w.j  av a  2  s.c o  m
 *
 * @param <T>        the generic type
 * @param c          the c
 * @param list       the list
 * @param value      the value
 * @param separators the separators
 */
public static <T extends Enum<?>> void parseEnumValueList(Class<T> c, List<T> list, String value,
        char... separators) {
    EwsUtilities.ewsAssert(c.isEnum(), "EwsUtilities.ParseEnumValueList", "T is not an enum type.");

    StringBuilder regexp = new StringBuilder();
    regexp.append("[");
    for (char s : separators) {
        regexp.append("[");
        regexp.append(Pattern.quote(s + ""));
        regexp.append("]");
    }
    regexp.append("]");

    String[] enumValues = value.split(regexp.toString());

    for (String enumValue : enumValues) {
        for (T o : c.getEnumConstants()) {
            if (o.toString().equals(enumValue)) {
                list.add(o);
            }
        }
    }
}

From source file:info.magnolia.content2bean.impl.EnumAwareConvertUtilsBean.java

@Override
public Converter lookup(Class clazz) {
    final Converter converter = super.lookup(clazz);
    // no specific converter for this class, so it's neither a String, (which has a default converter),
    // nor any known object that has a custom converter for it. It might be an enum !
    if (converter == null && clazz.isEnum()) {
        return enumConverter;
    }//from w  w w  .  j a v  a 2s.  c  o m
    return converter;
}

From source file:org.openmhealth.schema.service.SchemaClassServiceImpl.java

@PostConstruct
public void initializeSchemaIds() throws IllegalAccessException, InvocationTargetException,
        InstantiationException, NoSuchMethodException {

    Reflections reflections = new Reflections(SCHEMA_CLASS_PACKAGE);

    for (Class<? extends SchemaSupport> schemaClass : reflections.getSubTypesOf(SchemaSupport.class)) {

        if (schemaClass.isInterface() || Modifier.isAbstract(schemaClass.getModifiers())) {
            continue;
        }//from  w  ww .  jav a 2 s.co m

        SchemaId schemaId;

        if (schemaClass.isEnum()) {
            schemaId = schemaClass.getEnumConstants()[0].getSchemaId();
        } else {
            Constructor<? extends SchemaSupport> constructor = schemaClass.getDeclaredConstructor();
            constructor.setAccessible(true);
            schemaId = constructor.newInstance().getSchemaId();
        }

        schemaIds.add(schemaId);
    }
}

From source file:org.springframework.rest.documentation.boot.SwaggerDocumentationEndpoint.java

private void addModelForType(String type, Map<String, ClassDescriptor> responseClasses,
        Documentation documentation) {//from   ww w. ja  v  a2  s  .co m
    String name = getSwaggerDataType(type);
    if (documentation.getModels() == null || !documentation.getModels().containsKey(name)) {
        DocumentationSchema schema = new DocumentationSchema();

        ClassDescriptor classDescriptor = responseClasses.get(type);
        if (classDescriptor != null) {
            schema.setDescription(classDescriptor.getName());
        }

        try {
            Class<?> clazz = Class.forName(type);

            if (clazz.isEnum()) {
                Object[] enumConstants = clazz.getEnumConstants();
                List<String> values = new ArrayList<String>();
                for (Object enumConstant : enumConstants) {
                    values.add(enumConstant.toString());
                }
                schema.setAllowableValues(new DocumentationAllowableListValues(values));
            } else {
                BasicClassIntrospector introspector = new BasicClassIntrospector();

                Map<String, DocumentationSchema> properties = new HashMap<String, DocumentationSchema>();

                BasicBeanDescription descriptor = introspector.forSerialization(
                        this.objectMapper.getSerializationConfig(),
                        TypeFactory.defaultInstance().constructType(clazz),
                        this.objectMapper.getSerializationConfig());

                for (BeanPropertyDefinition property : descriptor.findProperties()) {
                    String propertyName = property.getName();
                    DocumentationSchema propertySchema = new DocumentationSchema();
                    MethodDescriptor methodDescriptor = classDescriptor
                            .getMethodDescriptor((Method) property.getAccessor().getAnnotated());
                    if (methodDescriptor != null) {
                        Class<?> propertyClass = Class.forName(methodDescriptor.getReturnType());

                        propertySchema.setDescription(methodDescriptor.getSummary());

                        if (propertyClass.isEnum()) {
                            Object[] enumConstants = propertyClass.getEnumConstants();
                            List<String> values = new ArrayList<String>();
                            for (Object enumConstant : enumConstants) {
                                values.add(enumConstant.toString());
                            }
                            propertySchema.setType("string");
                            propertySchema.setAllowableValues(new DocumentationAllowableListValues(values));
                        } else {
                            propertySchema.setType(getSwaggerDataType(methodDescriptor.getReturnType()));
                            addModelForType(methodDescriptor.getReturnType(), responseClasses, documentation);
                        }
                    }

                    properties.put(propertyName, propertySchema);
                }

                schema.setProperties(properties);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        documentation.addModel(name, schema);
    }
}