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:com.ejisto.modules.factory.impl.EnumFactory.java

@Override
public Enum<T> create(MockedField m, Enum<T> actualValue) {
    try {/*from  w w w  .  j a  v a  2s .  co m*/
        String name = m.getFieldValue();
        if (StringUtils.isEmpty(name)) {
            return actualValue;
        }
        @SuppressWarnings("unchecked")
        Class<Enum<T>> clazz = (Class<Enum<T>>) Class.forName(m.getFieldType());
        if (!clazz.isEnum()) {
            return actualValue;
        }
        Enum<T>[] enums = clazz.getEnumConstants();
        for (Enum<T> en : enums) {
            if (en.name().equals(name)) {
                return en;
            }
        }
        if (actualValue != null) {
            return actualValue;
        }
        return enums.length > 0 ? enums[0] : null;
    } catch (Exception ex) {
        log.warn(String.format("enum value not found for %s.", m), ex);
    }
    return actualValue;
}

From source file:org.efaps.admin.datamodel.attributetype.BitEnumType.java

/**
 * @param _attribute Attribute the enum class is defined for
 * @param _num       number from eFapsDatabase thta defines the enum
 * @return enum/*  w  w w .j  a  v  a  2s. c  om*/
 */
@Override
protected Object getEnum4Int(final Attribute _attribute, final Integer _num) {
    final AdvancedCache<String, Object> cache = InfinispanCache.get()
            .<String, Object>getIgnReCache(EnumType.CACHE);
    final String key = _attribute.getClassName() + "-" + _num;
    if (!cache.containsKey(key)) {
        final List<IBitEnum> ret = new ArrayList<IBitEnum>();
        try {
            final Class<?> clazz = Class.forName(_attribute.getClassName(), false,
                    EFapsClassLoader.getInstance());
            final Object[] consts = clazz.getEnumConstants();
            if (consts != null) {
                for (final Object cons : consts) {
                    if (BitEnumType.isSelected(_num, (IBitEnum) cons)) {
                        ret.add((IBitEnum) cons);
                    }
                }
            }
        } catch (final ClassNotFoundException e) {
            LOG.error("Could not read clazz.", e);
        }
        cache.put(key, ret);
    }
    return cache.get(key);
}

From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java

public static Object[][] getValidStartStages(@Nullable Class<? extends Enum> subStages) {

    if (subStages == null) {

        ////from ww  w  . j av a2s.c om
        // N.B. Tasks without defined sub-stages must accept these default start stages.
        //

        return new Object[][] { { null }, { TaskState.TaskStage.CREATED }, { TaskState.TaskStage.STARTED },
                { TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.FAILED },
                { TaskState.TaskStage.CANCELLED }, };
    }

    if (!subStages.isEnum() || subStages.getEnumConstants().length == 0) {
        throw new IllegalStateException("Class " + subStages.getName() + " is not a valid enum");
    }

    Enum[] enumConstants = subStages.getEnumConstants();
    List<Object[]> validStartStages = new ArrayList<>();
    validStartStages.add(new Object[] { null, null });
    validStartStages.add(new Object[] { TaskState.TaskStage.CREATED, null });
    for (int i = 0; i < enumConstants.length; i++) {
        validStartStages.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i] });
    }
    validStartStages.add(new Object[] { TaskState.TaskStage.FINISHED, null });
    validStartStages.add(new Object[] { TaskState.TaskStage.FAILED, null });
    validStartStages.add(new Object[] { TaskState.TaskStage.CANCELLED, null });

    Object[][] returnValue = new Object[validStartStages.size()][2];
    for (int i = 0; i < validStartStages.size(); i++) {
        returnValue[i][0] = validStartStages.get(i)[0];
        returnValue[i][1] = validStartStages.get(i)[1];
    }

    return returnValue;
}

From source file:net.kaczmarzyk.spring.data.jpa.domain.EqualEnum.java

private List<Enum<?>> findMatchingEnumConstants(Class<? extends Enum<?>> enumClass) {
    List<String> searchedNamesCopy = new ArrayList<>(Arrays.asList(searchedNames));
    List<Enum<?>> matchingEnumConstants = new ArrayList<>();
    Enum<?>[] enumConstants = enumClass.getEnumConstants();
    for (Enum<?> enumConstant : enumConstants) {
        Iterator<String> i = searchedNamesCopy.iterator();
        while (i.hasNext()) {
            if (enumConstant.name().equals(i.next())) {
                matchingEnumConstants.add(enumConstant);
                i.remove();//from w  w  w . ja v a2  s.  co m
            }
        }
    }
    if (searchedNamesCopy.size() > 0) {
        throw new IllegalArgumentException(
                "The following enum constants do not exists: " + StringUtils.join(searchedNamesCopy, ", "));
    }
    return matchingEnumConstants;
}

From source file:com.autentia.tnt.converter.EnumConverter.java

public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
    Class clazz = component.getValueBinding("value").getType(context);
    log.debug("getAsObject - clazz=" + clazz.getName());

    Enum ret = null;//from w ww . j  a v  a  2s.c o  m
    if (!StringUtils.isEmpty(value)) {
        try {
            Enum[] values = (Enum[]) clazz.getEnumConstants();
            ret = values[Integer.parseInt(value)];
            /*
            for( Enum val : values )
            {
                    if( val.name().equals(value) )
                    {
                            ret = val;
                            break;
                    }
            }
             */
        } catch (Exception e) {
            log.warn("getAsObject - exception converting value '" + value + "' to " + clazz.getName(), e);
            throw new ConverterException("Error converting value '" + value + "' to " + clazz.getName(), e);
        }

    }
    return ret;
}

From source file:co.marcin.novaguilds.enums.Config.java

public <E extends Enum> E toEnum(Class<E> clazz) {
    for (E enumConstant : clazz.getEnumConstants()) {
        if (enumConstant.name().equalsIgnoreCase(getString())) {
            return enumConstant;
        }//w w w  .java 2 s. c  o m
    }

    return null;
}

From source file:com.rvantwisk.gcodeparser.GCodeParser.java

/**
 * Returns a word count within teh current block
 * This is usefull to find multiple the same words within a modal group in the current block
 *
 * @param currentBlock/*from ww  w . j a va2 s  .  c  o  m*/
 * @param enumClass
 * @param <T>
 * @return
 */
private <T extends Enum<T>> int wordCount(Map<String, ParsedWord> currentBlock, Class<T> enumClass) {
    int wordCount = 0;

    T[] items = enumClass.getEnumConstants();

    for (T item : items) {
        if (hasWord(currentBlock, item.toString())) {
            wordCount++;
        }
    }
    return wordCount;
}

From source file:org.apache.empire.spring.EmpireReader.java

@Override
protected void getBeanProperty(Object bean, String property, Object value) {
    try {//w  ww.  j  a v a 2 s. c o  m
        if (bean == null)
            throw new InvalidArgumentException("bean", bean);
        if (StringUtils.isEmpty(property))
            throw new InvalidArgumentException("property", property);

        // Get descriptor
        PropertyDescriptor descriptor = BeanUtilsBean.getInstance().getPropertyUtils()
                .getPropertyDescriptor(bean, property);
        if (descriptor == null) {
            return; // Skip this property setter
        }
        // Check enum
        Class<?> type = descriptor.getPropertyType();
        if (type.isEnum()) {
            // Enum<?> ev = Enum.valueOf(type, value);
            boolean found = false;
            Enum<?>[] items = (Enum[]) type.getEnumConstants();
            for (int i = 0; i < items.length; i++) {
                Enum<?> item = items[i];
                if (ObjectUtils.compareEqual(item.name(), value)) {
                    value = item;
                    found = true;
                    break;
                }
            }
            // Enumeration value not found
            if (!found)
                throw new ItemNotFoundException(value);
        }

        // Set Property Value
        if (value != null) { // Bean utils will convert if necessary
            BeanUtils.setProperty(bean, property, value);
        } else { // Don't convert, just set
            PropertyUtils.setProperty(bean, property, null);
        }
    } catch (IllegalAccessException e) {
        log.error(bean.getClass().getName() + ": unable to set property '" + property + "'");
        throw new BeanPropertySetException(bean, property, e);
    } catch (InvocationTargetException e) {
        log.error(bean.getClass().getName() + ": unable to set property '" + property + "'");
        throw new BeanPropertySetException(bean, property, e);
    } catch (NoSuchMethodException e) {
        log.error(bean.getClass().getName() + ": unable to set property '" + property + "'");
        throw new BeanPropertySetException(bean, property, e);
    } catch (NullPointerException e) {
        log.error(bean.getClass().getName() + ": unable to set property '" + property + "'");
        throw new BeanPropertySetException(bean, property, e);
    }
}

From source file:com.xyxy.platform.modules.core.web.taglib.BSAbstractMultiCheckedElementTag.java

/**
 * Copy & Paste, .// www . jav  a  2s.  c o m
 */
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
    Object items = getItems();
    Object itemsObject = (items instanceof String ? evaluate("items", items) : items);

    String itemValue = getItemValue();
    String itemLabel = getItemLabel();
    String valueProperty = (itemValue != null ? ObjectUtils.getDisplayString(evaluate("itemValue", itemValue))
            : null);
    String labelProperty = (itemLabel != null ? ObjectUtils.getDisplayString(evaluate("itemLabel", itemLabel))
            : null);

    Class<?> boundType = getBindStatus().getValueType();
    if ((itemsObject == null) && (boundType != null) && boundType.isEnum()) {
        itemsObject = boundType.getEnumConstants();
    }

    if (itemsObject == null) {
        throw new IllegalArgumentException(
                "Attribute 'items' is required and must be a Collection, an Array or a Map");
    }

    if (itemsObject.getClass().isArray()) {
        Object[] itemsArray = (Object[]) itemsObject;
        for (int i = 0; i < itemsArray.length; i++) {
            Object item = itemsArray[i];
            writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i);
        }
    } else if (itemsObject instanceof Collection) {
        final Collection optionCollection = (Collection) itemsObject;
        int itemIndex = 0;
        for (Iterator it = optionCollection.iterator(); it.hasNext(); itemIndex++) {
            Object item = it.next();
            writeObjectEntry(tagWriter, valueProperty, labelProperty, item, itemIndex);
        }
    } else if (itemsObject instanceof Map) {
        final Map optionMap = (Map) itemsObject;
        int itemIndex = 0;
        for (Iterator it = optionMap.entrySet().iterator(); it.hasNext(); itemIndex++) {
            Map.Entry entry = (Map.Entry) it.next();
            writeMapEntry(tagWriter, valueProperty, labelProperty, entry, itemIndex);
        }
    } else {
        throw new IllegalArgumentException("Attribute 'items' must be an array, a Collection or a Map");
    }

    return SKIP_BODY;
}

From source file:com.autentia.intra.converter.EnumConverter.java

public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
    Class clazz = component.getValueBinding("value").getType(context);
    log.debug("getAsObject - clazz=" + clazz.getName());

    Enum ret = null;//w ww. jav  a 2  s  .  c o m
    if (!StringUtils.isEmpty(value)) {
        try {
            Enum[] values = (Enum[]) clazz.getEnumConstants();
            ret = values[Integer.parseInt(value)];
            /*
            for( Enum val : values )
            {
               if( val.name().equals(value) )
               {
                       ret = val;
                       break;
               }
            }
            */
        } catch (Exception e) {
            log.warn("getAsObject - exception converting value '" + value + "' to " + clazz.getName(), e);
            throw new ConverterException("Error converting value '" + value + "' to " + clazz.getName(), e);
        }

    }
    return ret;
}