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:demo.config.PropertyConverter.java

/**
 * Convert the specified value into a Java 5 enum.
 * //  w ww.j  av  a  2  s .  c  o  m
 * @param value
 *            the value to convert
 * @param cls
 *            the type of the enumeration
 * @return the converted value
 * @throws ConversionException
 *             thrown if the value cannot be converted to an enumeration
 * 
 * @since 1.5
 */
static <E extends Enum<E>> E toEnum(Object value, Class<E> cls) throws ConversionException {
    if (value.getClass().equals(cls)) {
        return cls.cast(value);
    } else if (value instanceof String) {
        try {
            return Enum.valueOf(cls, (String) value);
        } catch (Exception e) {
            throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName());
        }
    } else if (value instanceof Number) {
        try {
            E[] enumConstants = cls.getEnumConstants();
            return enumConstants[((Number) value).intValue()];
        } catch (Exception e) {
            throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName());
        }
    } else {
        throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName());
    }
}

From source file:org.xwiki.wysiwyg.server.internal.plugin.macro.XWikiMacroService.java

/**
 * NOTE: We can't send a {@link Type} instance to the client side because GWT can't serialize it so we have to
 * convert it to a {@link ParameterType} instance.
 * //from   w  ww.j a  v a  2 s  .c om
 * @param type the type that defines the values a macro parameter can have
 * @return the parameter type associated with the given type
 */
private ParameterType createMacroParameterType(Type type) {
    ParameterType parameterType = new ParameterType();
    if (type instanceof Class) {
        Class<?> parameterClass = (Class<?>) type;
        parameterType.setName(parameterClass.getName());
        if (parameterClass.isEnum()) {
            Object[] parameterClassConstants = parameterClass.getEnumConstants();
            Map<String, String> parameterTypeConstants = new LinkedHashMap<String, String>();
            for (int i = 0; i < parameterClassConstants.length; i++) {
                String constant = String.valueOf(parameterClassConstants[i]);
                // We leave the constant unlocalized for now.
                parameterTypeConstants.put(constant, constant);
            }
            parameterType.setEnumConstants(parameterTypeConstants);
        }
    }
    return parameterType;
}

From source file:fr.zcraft.zlib.components.commands.Command.java

protected <T extends Enum> T getEnumParameter(int index, Class<T> enumType) throws CommandException {
    Enum[] enumValues = enumType.getEnumConstants();
    String parameter = args[index].toLowerCase();

    for (Enum value : enumValues) {
        if (value.toString().toLowerCase().equals(parameter))
            return (T) value;
    }/*from w w w .  j ava2s .co  m*/

    throw new CommandException(this, Reason.INVALID_PARAMETERS, invalidParameterString(index, enumValues));
}

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;
        }/*ww  w .ja v  a2 s .c o 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:com.l2jfree.config.model.ConfigFieldInfo.java

public void print(PrintWriter out, PrintMode mode) {
    if (getBeginningGroup() != null && (mode != PrintMode.MODIFIED || getBeginningGroup().isModified())) {
        out.println("########################################");
        out.println("## " + getConfigGroupBeginning().name());

        if (!ArrayUtils.isEmpty(getConfigGroupBeginning().comment()))
            for (String line : getConfigGroupBeginning().comment())
                out.println("# " + line);

        out.println();//w  w w.j  ava  2  s.c  o m
    }

    if (mode != PrintMode.MODIFIED || isModified()) {
        if (!ArrayUtils.isEmpty(getConfigField().comment()))
            for (String line : getConfigField().comment())
                out.println("# " + line);

        out.println("# ");
        out.println("# Default: " + getDefaultValue());
        if (getField().getType().isEnum())
            out.println("# Available: " + StringUtils.join(getField().getType().getEnumConstants(), "|"));
        else if (getField().getType().isArray()) {
            final Class<?> fieldComponentType = getField().getType().getComponentType();
            if (fieldComponentType.isEnum())
                out.println("# Available: " + StringUtils.join(fieldComponentType.getEnumConstants(), ","));
        }
        out.println("# ");
        out.println(getName() + " = "
                + (mode == null || mode == PrintMode.DEFAULT ? getDefaultValue() : getCurrentValue()));
        out.println();
    }

    if (getEndingGroup() != null && (mode != PrintMode.MODIFIED || getEndingGroup().isModified())) {
        if (!ArrayUtils.isEmpty(getConfigGroupEnding().comment()))
            for (String line : getConfigGroupEnding().comment())
                out.println("# " + line);

        out.println("## " + getConfigGroupEnding().name());
        out.println("########################################");

        out.println();
    }
}

From source file:utils.database.sqlite.data.AFieldData.java

/**
 * Create and initialize the object.//from  w  ww  . j a va2 s. co  m
 * 
 * @param t
 */
public AFieldData(Class<? extends IColumns> c, ITables t) {
    this.tab = t;
    IColumns[] value = c.getEnumConstants();
    init(value);

}

From source file:com.happyblueduck.lembas.datastore.LembasEntity.java

public void readField(Field f, Object value) throws IllegalAccessException {
    if (f.getType().isEnum()) {

        Class z = f.getType();
        Object[] cons = z.getEnumConstants();
        int intValue = -1;
        if (value instanceof Long)
            intValue = ((Long) value).intValue();

        for (int i = 0; i < cons.length; i++) {
            if (i == intValue) {
                f.set(this, Enum.valueOf((Class<Enum>) f.getType(), cons[i].toString()));
            }//from  w  w  w . j a  va2 s . c  om
        }
    } else {
        f.set(this, value);
    }
}

From source file:org.wso2.javaagent.JDBCClassTransformer.java

/**
 * Check whether method name available in enum
 *
 * @param value uppercase name of the processing method
 * @param enumClass enumeration class/*from  w  w  w.ja  va 2 s  .  c  o m*/
 * @param <E> The enum type subclass
 * @return {@code true} if the method name in enum, {@code false} otherwise
 */
public <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
    for (E enumValue : enumClass.getEnumConstants()) {
        if (enumValue.name().equals(value)) {
            return true;
        }
    }
    return false;
}

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

private void addModelForType(String type, Map<String, ClassDescriptor> responseClasses,
        Documentation documentation) {/* ww w . ja va  2  s .c  om*/
    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);
    }
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.virtual.DisplayTextVirtualDatapoint.java

/**
 * Returns a string array with all the constants in the Enum.
 *///from   w ww.ja  v a  2  s. c o m
private String[] getEnumNames(Class<? extends Enum<?>> e) {
    return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}