Example usage for java.lang Class getEnumConstants

List of usage examples for java.lang Class getEnumConstants

Introduction

In this page you can find the example usage for java.lang Class getEnumConstants.

Prototype

public T[] getEnumConstants() 

Source Link

Document

Returns the elements of this enum class or null if this Class object does not represent an enum type.

Usage

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

/**
 * Parses an enum value list./* w ww .  j a v  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:org.structr.files.cmis.CMISRepositoryService.java

private MutablePropertyDefinition createProperty(final Class type, final PropertyKey key) {

    // include all dynamic and CMIS-enabled keys in definition
    if (key.isDynamic() || key.isCMISProperty()) {

        // only include primitives here
        final TypeDefinitionFactory factory = TypeDefinitionFactory.newInstance();
        final PropertyType dataType = key.getDataType();

        if (dataType != null) {

            final String propertyId = key.jsonName();
            final String displayName = propertyId;
            final String description = StringUtils.capitalize(propertyId);
            final Class declaringClass = key.getDeclaringClass();
            final boolean isInherited = !type.getSimpleName().equals(declaringClass.getSimpleName());
            final Cardinality cardinality = Cardinality.SINGLE;
            final Updatability updatability = Updatability.READWRITE;
            final boolean required = key.isNotNull();
            final boolean queryable = key.isIndexed();
            final boolean orderable = key.isIndexed();

            final MutablePropertyDefinition property = factory.createPropertyDefinition(propertyId, displayName,
                    description, dataType, cardinality, updatability, isInherited, required, queryable,
                    orderable);//from   ww w .j a  v a 2s  . c  o m

            // add enum choices if present
            final Class valueType = key.valueType();
            if (valueType != null && valueType.isEnum()) {

                final List<Choice> choices = new LinkedList<>();

                for (final Object option : valueType.getEnumConstants()) {

                    final String optionName = option.toString();

                    choices.add(factory.createChoice(optionName, optionName));
                }

                property.setIsOpenChoice(false);
                property.setChoices(choices);
            }

            return property;
        }
    }

    return null;
}

From source file:de.escalon.hypermedia.spring.ActionInputParameter.java

private Object[] getPossibleValues(MethodParameter methodParameter, AnnotatedParameters actionDescriptor) {
    try {/*from w w  w  .j ava 2 s  .  c o  m*/
        Class<?> parameterType = methodParameter.getNestedParameterType();
        Object[] possibleValues;
        Class<?> nested;
        if (Enum[].class.isAssignableFrom(parameterType)) {
            possibleValues = parameterType.getComponentType().getEnumConstants();
        } else if (Enum.class.isAssignableFrom(parameterType)) {
            possibleValues = parameterType.getEnumConstants();
        } else if (Collection.class.isAssignableFrom(parameterType)
                && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) {
            possibleValues = nested.getEnumConstants();
        } else {
            Select select = methodParameter.getParameterAnnotation(Select.class);
            if (select != null) {
                Class<? extends Options> optionsClass = select.options();
                Options options = optionsClass.newInstance();
                // collect call values to pass to options.get
                List<Object> from = new ArrayList<Object>();
                for (String paramName : select.args()) {
                    AnnotatedParameter parameterValue = actionDescriptor.getAnnotatedParameter(paramName);
                    if (parameterValue != null) {
                        from.add(parameterValue.getCallValue());
                    }
                }

                Object[] args = from.toArray();
                possibleValues = options.get(select.value(), args);
            } else {
                possibleValues = new Object[0];
            }
        }
        return possibleValues;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spotify.docgenerator.DocgeneratorMojo.java

private void processEnum(Sink sink, String className) {
    Class<?> clazz = getClassForNameIsh(sink, className);
    if (clazz == null) {
        sink.text("Was not able to find class: " + className);
        sink.lineBreak();/*ww w . j  a va 2s  .  c om*/
        return;
    }
    if (clazz.isEnum()) {
        classHeading(sink, className);
        final Object[] constants = clazz.getEnumConstants();
        final List<String> constantsWrapped = Lists.newArrayList();
        for (Object c : constants) {
            constantsWrapped.add("\"" + c + "\"");
        }
        sink.text("Enumerated Type.  Valid values are: ");
        sink.monospaced();
        sink.text(Joiner.on(", ").join(constantsWrapped));
        sink.monospaced_();
        sink.lineBreak();
    } else {
        sink.text("!??!?!!?" + clazz);
        sink.lineBreak();
    }

}

From source file:de.escalon.hypermedia.spring.SpringActionInputParameter.java

public Object[] getPossibleValues(MethodParameter methodParameter, ActionDescriptor actionDescriptor) {
    try {//from ww  w .  j ava 2 s. com
        Class<?> parameterType = methodParameter.getNestedParameterType();
        Object[] possibleValues;
        Class<?> nested;
        if (Enum[].class.isAssignableFrom(parameterType)) {
            possibleValues = parameterType.getComponentType().getEnumConstants();
        } else if (Enum.class.isAssignableFrom(parameterType)) {
            possibleValues = parameterType.getEnumConstants();
        } else if (Collection.class.isAssignableFrom(parameterType)
                && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) {
            possibleValues = nested.getEnumConstants();
        } else {
            Select select = methodParameter.getParameterAnnotation(Select.class);
            if (select != null) {
                Class<? extends Options> optionsClass = select.options();
                Options options = optionsClass.newInstance();
                // collect call values to pass to options.get
                List<Object> from = new ArrayList<Object>();
                for (String paramName : select.args()) {
                    ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName);
                    if (parameterValue != null) {
                        from.add(parameterValue.getValue());
                    }
                }

                Object[] args = from.toArray();
                possibleValues = options.get(select.value(), args);
            } else {
                possibleValues = new Object[0];
            }
        }
        return possibleValues;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.ItemRestriction.java

private Enum getRepoEnumValue(Enum schemaValue, Class repoType) throws QueryException {
    if (schemaValue == null) {
        return null;
    }/*from   w w w.  j av a2s .  c o  m*/

    if (SchemaEnum.class.isAssignableFrom(repoType)) {
        return (Enum) RUtil.getRepoEnumValue(schemaValue, repoType);
    }

    Object[] constants = repoType.getEnumConstants();
    for (Object constant : constants) {
        Enum e = (Enum) constant;
        if (e.name().equals(schemaValue.name())) {
            return e;
        }
    }

    throw new QueryException(
            "Unknown enum value '" + schemaValue + "', which is type of '" + schemaValue.getClass() + "'.");
}

From source file:com.heliosphere.demeter.base.runner.AbstractRunner.java

/**
 * Checks the definition of the parameters against their enumeration class.
 * <hr>//  w w  w. ja v  a  2 s. c  o  m
 * @param clazz Parameter enumeration class.
 * @throws ParameterException Thrown in case an error occurred when validating a parameter type against its enumeration class.
 */
@SuppressWarnings({ "unchecked", "rawtypes", "nls" })
private final void checkParameterDefinitionAgainstEnumeration(@NonNull final Class clazz)
        throws ParameterException {
    Class<? extends Enum<? extends IParameterType>> enumeration = clazz;
    List<Enum<? extends IParameterType>> list = (List<Enum<? extends IParameterType>>) Arrays
            .asList(enumeration.getEnumConstants());
    for (Enum<? extends IParameterType> e : list) {
        boolean found = false;
        for (IParameterConfiguration p : configuration.getContent().getElements()) {
            if (p.getType() == e) {
                found = true;
                break;
            }
        }
        if (!found && !e.toString().equals("UNKNOWN")) {
            throw new ParameterException(String.format(
                    "Unable to find parameter name: '%1s' in file: '%2s' corresponding to enumeration class: %3s for enumerated value: %4s",
                    ((IParameterType) e).getName(), configuration.getResource().getFile().getName(),
                    clazz.getSimpleName(), e.toString()));
        }
    }
}

From source file:com.grepcurl.random.ObjectGenerator.java

@SuppressWarnings("unused")
public <T> T generate(Class<T> klass, Object... constructorArgs) {
    Validate.notNull(klass);//from  w w  w  .  ja  v  a2s  .  com
    Validate.notNull(constructorArgs);
    if (verbose) {
        log(String.format("generating object of type: %s, with args: %s", klass,
                Arrays.toString(constructorArgs)));
    }
    try {
        Deque<Object> objectStack = new ArrayDeque<>();
        Class[] constructorTypes = _toClasses(constructorArgs);
        T t;
        if (klass.isEnum()) {
            int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1);
            t = klass.getEnumConstants()[randomOrdinal];
        } else {
            t = klass.getConstructor(constructorTypes).newInstance(constructorArgs);
        }
        objectStack.push(t);
        Method[] methods = klass.getMethods();
        for (Method method : methods) {
            _processMethod(method, new SetterOverrides(), t, objectStack);
        }
        objectStack.pop();
        return t;
    } catch (Exception e) {
        throw new FailedRandomObjectGenerationException(e);
    }
}

From source file:org.bimserver.tools.generators.ProtocolBuffersGenerator.java

private String createEnum(StringBuilder sb, Class<?> clazz) {
    if (generatedClasses.containsKey(clazz)) {
        return generatedClasses.get(clazz);
    } else {//from  w  w w  .ja v a  2  s.  c o m
        generatedClasses.put(clazz, clazz.getSimpleName());
    }
    sb.append("enum " + clazz.getSimpleName() + "{\n");
    int counter = 0;
    for (Object o : clazz.getEnumConstants()) {
        sb.append("\t" + o.toString() + " = " + (counter++) + ";\n");
    }
    sb.append("}\n\n");
    return clazz.getSimpleName();
}

From source file:org.candlepin.swagger.CandlepinSwaggerModelConverter.java

protected void pAddEnumProps(Class<?> propClass, Property property) {
    final boolean useIndex = pMapper.isEnabled(SerializationFeature.WRITE_ENUMS_USING_INDEX);
    final boolean useToString = pMapper.isEnabled(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

    @SuppressWarnings("unchecked")
    Class<Enum<?>> enumClass = (Class<Enum<?>>) propClass;
    for (Enum<?> en : enumClass.getEnumConstants()) {
        String n;/*from   w ww .ja  v a 2  s  . co  m*/
        if (useIndex) {
            n = String.valueOf(en.ordinal());
        } else if (useToString) {
            n = en.toString();
        } else {
            n = pIntr.findEnumValue(en);
        }
        if (property instanceof StringProperty) {
            StringProperty sp = (StringProperty) property;
            sp._enum(n);
        }
    }
}