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:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

private static ObjectNode buildChoicesNode(final ObjectMapper objectMapper, final Type heapValueType,
        final SchemaLoader schemaLoader) {

    if (heapValueType == null || !(heapValueType instanceof Class<?>)) {
        return null;
    }//  ww  w  .ja va 2s.c om

    final Class<?> choicesEnumClass = (Class<?>) heapValueType;

    if (!choicesEnumClass.isEnum()) {
        return null;
    }

    final URI choicesUri = schemaLoader.getTypeUri(choicesEnumClass);
    final String choicesName = choicesEnumClass.getSimpleName();
    final ObjectNode choicesNode = objectMapper.createObjectNode();

    choicesNode.put(PropertyName.title.name(), choicesName);
    choicesNode.put(PropertyName.uri.name(), choicesUri.toString());

    // TODO: Only embed the choices once per schema to lighten the download?
    final Object[] enumConstants = choicesEnumClass.getEnumConstants();
    if (enumConstants != null && enumConstants.length > 0) {
        final ArrayNode valuesNode = objectMapper.createArrayNode();

        choicesNode.put(PropertyName.values.name(), valuesNode);

        for (final Object enumConstant : enumConstants) {
            final String choice = String.valueOf(enumConstant);
            valuesNode.add(choice);
        }
    }

    return choicesNode;
}

From source file:pl.themolka.cmds.packet.TitlePacket.java

@Override
public Object handle() {
    try {//from   w  w  w .ja  v a  2s  .  co  m
        String json = "{\"text\": \"" + this.getTitle() + "\"}";
        Class<?> titleEnum = Packet.getNMSClass("EnumTitleAction");
        Class<?> jsonParser = Packet.getNMSClass("ChatSerializer");

        Object[] values = titleEnum.getEnumConstants();
        Object value = null;
        switch (this.getType()) {
        case SUBTITLE:
            value = values[1];
            break;
        case TITLE:
            value = values[0];
            break;
        }

        Object component = jsonParser.getDeclaredMethod("a", new Class[] { String.class }).invoke(null,
                new Object[] { json });
        Constructor<? extends Object> constructor = this.getPacketClass()
                .getConstructor(new Class[] { titleEnum, Packet.getNMSClass("IChatBaseComponent") });
        return constructor.newInstance(titleEnum.cast(value), component);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | InstantiationException ex) {
        Logger.getLogger(TitlePacket.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.openmainframe.ade.impl.PropertyAnnotation.java

@SuppressWarnings({ "unchecked" })
static private void setProps(Object obj, Map<String, ? extends Object> props, Pattern filter, boolean safe)
        throws MissingPropertyException, IllegalArgumentException {
    final Class<?> annotatedClass = obj.getClass();
    final Set<String> keyset = new TreeSet<String>(props.keySet());

    for (Field field : annotatedClass.getDeclaredFields()) {
        final Property annos = field.getAnnotation(Property.class);
        if (annos != null) {
            // skip missing and non-required properties
            final String key = annos.key();
            if (!props.containsKey(key)) {
                if (annos.required()) {
                    throw new MissingPropertyException("Missing property: " + key);
                } else {
                    // no value for non-required property
                    continue;
                }// w ww .  j  a  v a 2 s .  co m
            }

            final Class<? extends IPropertyFactory<?>> factoryClass = annos.factory();

            final Object rawVal = props.get(key);
            final Type fieldType = field.getGenericType();
            Object val = null;
            if (factoryClass != Property.NULL_PROPERTY_FACTORY.class) {
                // check if this factory is eligible for creating this property
                final Type factoryProductType = resolveActualTypeArgs(factoryClass, IPropertyFactory.class)[0];
                if (!TypeUtils.isAssignable(factoryProductType, fieldType)) {
                    throw new IllegalArgumentException("The factory provided for the field: " + field.getName()
                            + " is not compatible for creating object of type: " + fieldType);
                }

                Constructor<? extends IPropertyFactory<?>> constructor;
                try {
                    constructor = factoryClass.getConstructor();
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                            "Missing empty constructor in: " + factoryClass.getName(), e);
                }

                IPropertyFactory<?> factory;
                try {
                    factory = constructor.newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException("Failed instantiating: " + factoryClass.getName(), e);
                }

                try {
                    val = factory.create(rawVal);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Failed extractring property value: " + key, e);
                }
            } else if (TypeUtils.isAssignable(rawVal.getClass(), fieldType)) {
                val = rawVal;
            } else if (rawVal.getClass().equals(String.class)) {
                final Class<?> fieldClass = field.getType();
                final String stringVal = (String) rawVal;
                if (fieldClass == Integer.class || fieldClass == int.class) {
                    try {
                        val = Integer.parseInt(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing integer value for property: " + key,
                                e);
                    }
                } else if (fieldClass == Double.class || fieldClass == double.class) {
                    try {
                        val = Double.parseDouble(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing double value for property: " + key,
                                e);
                    }
                } else if (fieldClass == Boolean.class || fieldClass == boolean.class) {
                    try {
                        val = Boolean.parseBoolean(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing boolean value for property: " + key,
                                e);
                    }
                } else if (fieldClass == String.class) {
                    // should never have reached here, since String is assignable from String
                    val = stringVal;
                } else if (fieldClass.isEnum()) {
                    Class<Enum> fieldEnum;
                    try {
                        fieldEnum = (Class<Enum>) fieldClass;
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Failed casting to Class<Enum> field class: " + fieldClass.getName(), e);
                    }
                    try {
                        val = Enum.valueOf(fieldEnum, stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing enum value for property: " + key
                                + "\n\t possible values: " + Arrays.toString(fieldEnum.getEnumConstants()), e);
                    }
                } else {
                    // try to find String constructor for field, or else throw exception
                    Constructor<?> constructor;
                    try {
                        constructor = fieldClass.getConstructor(String.class);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Field: " + field.getName() + " of type "
                                + fieldClass
                                + " is not one of the known property type (Integer, Double, Boolean, String, Enum), does not have a String constructor and no custom factory is defined in the annotation!",
                                e);
                    }
                    try {
                        val = constructor.newInstance(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Could not create a new instance for "
                                + field.getName() + " using the String constructor for type: " + fieldClass, e);
                    }
                }
            }

            if (val == null) {
                throw new IllegalArgumentException("For the key " + key
                        + ", we expect the value to be either assignable to " + fieldType + " or a String");
            }

            try {
                field.setAccessible(true);
                field.set(obj, val);
                keyset.remove(key);
            } catch (SecurityException e) {
                throw new SecurityException("Field " + field.getName()
                        + " is not accesible, and could not be set as accesible (probably due to PermissionManager)",
                        e);
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Failed setting field: " + field.getName() + " with value: " + val, e);
            }
        }
    }
    if (safe && !keyset.isEmpty()) {
        throw new IllegalArgumentException("Unrecongnized arguments in the properties: " + keyset.toString());
    }
}

From source file:org.apache.hadoop.hdfs.util.EnumCounters.java

/**
 * Construct counters for the given enum constants.
 * @param enumClass the enum class of the counters.
 *///from   www . ja va2  s  . c o  m
public EnumCounters(final Class<E> enumClass) {
    final E[] enumConstants = enumClass.getEnumConstants();
    Preconditions.checkNotNull(enumConstants);
    this.enumClass = enumClass;
    this.counters = new long[enumConstants.length];
}

From source file:io.konik.utils.RandomInvoiceGenerator.java

private Object getEnum(Class<?> type) {
    Object[] enumConstants = type.getEnumConstants();
    return enumConstants[random.nextInt(enumConstants.length)];
}

From source file:org.sleeksnap.Configuration.java

@SuppressWarnings("unchecked")
public <T> T getEnumValue(final String key, final Class<?> class1) {
    if (class1.isEnum()) {
        return (T) class1.getEnumConstants()[getInteger(key)];
    }/*from ww  w.j a  va  2s.c  o m*/
    return null;
}

From source file:org.apache.hadoop.hdfs.util.EnumCounters.java

public EnumCounters(final Class<E> enumClass, long defaultVal) {
    final E[] enumConstants = enumClass.getEnumConstants();
    Preconditions.checkNotNull(enumConstants);
    this.enumClass = enumClass;
    this.counters = new long[enumConstants.length];
    reset(defaultVal);/*from   w w  w.ja va  2  s .c o  m*/
}

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumWithNullValue() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumWithNullValue.json", "com.example");

    Class<Enum> emptyEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithNullValue");

    assertThat(emptyEnumClass.getEnumConstants().length, is(1));

}

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumWithEmptyStringAsValue() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumWithEmptyString.json", "com.example");

    Class<Enum> emptyEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithEmptyString");

    assertThat(emptyEnumClass.getEnumConstants()[0].name(), is("__EMPTY__"));

}