List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:org.rhq.enterprise.server.search.assist.AbstractSearchAssistant.java
protected final List<String> filter(Class<? extends Enum<?>> enumType, String filter, boolean includeAnyOption) { List<String> results = new ArrayList<String>(); if (includeAnyOption && "any".contains(filter)) { results.add("any"); }//w w w . j a v a2 s. c o m for (Enum<?> next : enumType.getEnumConstants()) { String enumName = next.name().toLowerCase(); if (filter == null || filter.equals("") || enumName.contains(filter)) { results.add(enumName); } } return Collections.unmodifiableList(results); }
From source file:org.bimserver.shared.pb.ProtocolBuffersConverter.java
private Object convertFieldValue(SField field, Object val) throws ConvertException { if (val instanceof EnumValueDescriptor) { EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor) val; Class<?> enumClass; try {// www . j a v a 2s.c o m enumClass = Class .forName("org.bimserver.interfaces.objects." + enumValueDescriptor.getType().getName()); for (Object v : enumClass.getEnumConstants()) { Enum<?> e = (Enum<?>) v; if (e.ordinal() == enumValueDescriptor.getNumber()) { val = e; break; } } } catch (ClassNotFoundException e) { LOGGER.error("", e); } return val; } else if (field.getType().getInstanceClass() == Date.class) { return new Date((Long) val); } else if (field.getType().getInstanceClass() == DataHandler.class) { ByteString byteString = (ByteString) val; ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource("test", byteString.toByteArray()); return new DataHandler(byteArrayDataSource); } else if (val instanceof DynamicMessage) { return convertProtocolBuffersMessageToSObject((DynamicMessage) val, null, field.isAggregate() ? field.getGenericType() : field.getType()); } else { return val; } }
From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java
private void setDataType(Method method, AppPropertyEntity entity) { Class<?> returnType = method.getReturnType(); if (returnType.isPrimitive()) { if (returnType == boolean.class) entity.setDataTypeName(datatypes.getIdByJavaClass(Boolean.class)); if (returnType == int.class) entity.setDataTypeName(datatypes.getIdByJavaClass(Integer.class)); if (returnType == long.class) entity.setDataTypeName(datatypes.getIdByJavaClass(Long.class)); if (returnType == double.class || returnType == float.class) entity.setDataTypeName(datatypes.getIdByJavaClass(Double.class)); } else if (returnType.isEnum()) { entity.setDataTypeName("enum"); EnumStore enumStoreAnn = method.getAnnotation(EnumStore.class); if (enumStoreAnn != null && enumStoreAnn.value() == EnumStoreMode.ID) { //noinspection unchecked Class<EnumClass> enumeration = (Class<EnumClass>) returnType; entity.setEnumValues(Arrays.asList(enumeration.getEnumConstants()).stream() .map(ec -> String.valueOf(ec.getId())).collect(Collectors.joining(","))); } else {// ww w. j av a2s .co m entity.setEnumValues(Arrays.asList(returnType.getEnumConstants()).stream().map(Object::toString) .collect(Collectors.joining(","))); } } else { Datatype<?> datatype = datatypes.get(returnType); if (datatype != null) entity.setDataTypeName(datatypes.getId(datatype)); else entity.setDataTypeName(datatypes.getIdByJavaClass(String.class)); } String dataTypeName = entity.getDataTypeName(); if (!dataTypeName.equals("enum")) { Datatype datatype = Datatypes.get(dataTypeName); String v = null; try { v = entity.getDefaultValue(); datatype.parse(v); v = entity.getCurrentValue(); datatype.parse(v); } catch (ParseException e) { log.debug("Cannot parse '{}' with {} datatype, using StringDatatype for property {}", v, datatype, entity.getName()); entity.setDataTypeName(datatypes.getIdByJavaClass(String.class)); } } }
From source file:nc.noumea.mairie.appock.core.viewmodel.AbstractViewModel.java
/** * Mthode utilitaire, pour lister les valeurs d'une numration (dans l'ordre de leur dclaration), avec la possibilit d'insrer en tte la valeur null. * //from w w w .j a v a2s . c o m * @param enumClassName nom complet de la classe (avec le package, ex : "nc.noumea.mairie.appock.enums.TypeConfig") * @param insertNull indique s'il faut insrer en tte de la liste rsultat la valeur null * @return la liste des valeurs numres, dans l'ordre de leur dclaration (avec null en tte optionnellement) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public ListModelList<?> getListeEnum(String enumClassName, boolean insertNull) { try { Class<?> classe = Class.forName(enumClassName); ListModelList result = new ListModelList(classe.getEnumConstants()); if (insertNull) { result.add(0, null); } return result; } catch (ClassNotFoundException e) { log.error("erreur sur getListeEnum", e); Messagebox.show(e.toString()); } return null; }
From source file:edu.utah.further.core.util.math.random.RandomUtilService.java
/** * Generate a random enumerated type.//from w w w. java 2 s . co m * * @param <E> * enum type * @param enumType * the Class object of the enumerated type * @return random enum constant */ public <E extends Enum<E>> E randomEnum(final Class<E> enumType) { final E[] values = enumType.getEnumConstants(); return values[randomInteger(0, values.length - 1)]; }
From source file:com.haulmont.cuba.web.gui.components.WebAbstractOptionsField.java
@Override public void setOptionsEnum(Class<? extends EnumClass> optionsEnum) { Object currentValue = null;//ww w . j ava 2s .co m if (metaProperty != null) { currentValue = component.getValue(); } List options = Arrays.asList(optionsEnum.getEnumConstants()); setComponentContainerDs(createEnumContainer(options)); setCaptionMode(CaptionMode.ITEM); if (metaProperty != null) { component.setValue(currentValue); } this.optionsEnum = optionsEnum; }
From source file:org.rhq.enterprise.gui.legacy.taglib.ConstantsTag.java
public int doEndTag() throws JspException { try {/* w w w . j a v a 2 s . c o m*/ JspWriter out = pageContext.getOut(); if (className == null) { className = pageContext.getServletContext().getInitParameter(constantsClassNameParam); } if (validate(out)) { // we're misconfigured. getting this far // is a matter of what our failure mode is; // if we haven't thrown an Error, carry on log.debug("constants tag misconfigured"); return EVAL_PAGE; } Map<String, String> fieldMap; if (constants.containsKey(className)) { // we cache the result of the constant's class // reflection field walk as a map fieldMap = (Map<String, String>) constants.get(className); } else { fieldMap = new HashMap<String, String>(); Class typeClass = Class.forName(className); if (typeClass.isEnum()) { for (Object enumConstantObj : typeClass.getEnumConstants()) { Enum enumConstant = (Enum) enumConstantObj; // Set name *and* value to enum name (e.g. name of ResourceCategory.PLATFORM = "PLATFORM") // NOTE: We do not set the value to enumConstant.ordinal(), because there is no way to // convert the ordinal value back to an Enum (i.e. no Enum.valueOf(int ordinal) method). fieldMap.put(enumConstant.name(), enumConstant.name()); } } else { Object instance = typeClass.newInstance(); Field[] fields = typeClass.getFields(); for (Field field : fields) { // string comparisons of class names should be cheaper // than reflective Class comparisons, the asumption here // is that most constants are Strings, ints and booleans // but a minimal effort is made to accomadate all types // and represent them as String's for our tag's output String fieldType = field.getType().getName(); String strVal; if (fieldType.equals("java.lang.String")) { strVal = (String) field.get(instance); } else if (fieldType.equals("int")) { strVal = Integer.toString(field.getInt(instance)); } else if (fieldType.equals("boolean")) { strVal = Boolean.toString(field.getBoolean(instance)); } else if (fieldType.equals("char")) { strVal = Character.toString(field.getChar(instance)); } else if (fieldType.equals("double")) { strVal = Double.toString(field.getDouble(instance)); } else if (fieldType.equals("float")) { strVal = Float.toString(field.getFloat(instance)); } else if (fieldType.equals("long")) { strVal = Long.toString(field.getLong(instance)); } else if (fieldType.equals("short")) { strVal = Short.toString(field.getShort(instance)); } else if (fieldType.equals("byte")) { strVal = Byte.toString(field.getByte(instance)); } else { strVal = field.get(instance).toString(); } fieldMap.put(field.getName(), strVal); } } // cache the result constants.put(className, fieldMap); } if ((symbol != null) && !fieldMap.containsKey(symbol)) { // tell the developer that he's being a dummy and what // might be done to remedy the situation // TODO: what happens if the constants change? // do we need to throw a JspException, here? - mtk String err1 = symbol + " was not found in " + className + "\n"; String err2 = err1 + "use <constants:diag classname=\"" + className + "\"/>\n" + "to figure out what you're looking for"; log.error(err2); die(out, err1); } if (varSpecified) { doSet(fieldMap); } else { doOutput(fieldMap, out); } } catch (JspException e) { throw e; } catch (Exception e) { log.debug("doEndTag() failed: ", e); throw new JspException("Could not access constants tag", e); } return EVAL_PAGE; }
From source file:org.vulpe.view.tags.Functions.java
/** * * @param bean/* www . ja v a 2 s .c o m*/ * @param field * @param removeEnumItems * @return * @throws JspException */ public static List listInField(final Object bean, final String field, final String removeEnumItems) throws JspException { try { if (bean == null) { return null; } final List list = new ArrayList(); final String[] fieldParts = field.replace(".id", "").split("\\."); Class<?> fieldClass = null; if (fieldParts.length == 1) { fieldClass = VulpeReflectUtil.getFieldClass(bean.getClass(), fieldParts[0]); } else { int count = 1; Class<?> parentClass = bean.getClass(); for (final String fieldPart : fieldParts) { parentClass = VulpeReflectUtil.getFieldClass(parentClass, fieldPart); ++count; if (count == fieldParts.length) { fieldClass = VulpeReflectUtil.getFieldClass(parentClass, fieldParts[fieldParts.length - 1]); } } } if (fieldClass.isEnum()) { int count = 0; for (final Object item : fieldClass.getEnumConstants()) { if (StringUtils.isNotEmpty(removeEnumItems)) { boolean remove = false; final String[] items = removeEnumItems.split(","); for (final String eItem : items) { if ((NumberUtils.isNumber(eItem) && Integer.valueOf(eItem) == count) || item.toString().equals(eItem)) { remove = true; break; } } ++count; if (remove) { continue; } } list.add(new ValueBean(item.toString(), findText(fieldClass.getName().concat(".").concat(item.toString())))); } } return list; } catch (Exception e) { throw new JspException(e); } }
From source file:org.jsonschema2pojo.integration.EnumIT.java
@Test @SuppressWarnings("unchecked") public void enumWithNoValidCharactersForIdentifier() throws Exception { ClassLoader resultsClassLoader = schemaRule .generateAndCompile("/schema/enum/enumWithNoValidCharactersForIdentifier.json", "com.example"); Class<Enum> enumClass = (Class<Enum>) resultsClassLoader .loadClass("com.example.EnumWithNoValidCharactersForIdentifier"); assertThat(enumClass.getEnumConstants()[0].name(), is("__EMPTY__")); assertThat(enumClass.getEnumConstants()[1].name(), is("__EMPTY___")); assertThat(enumClass.getEnumConstants()[2].name(), is("__EMPTY____")); assertThat(enumClass.getEnumConstants()[0].toString(), is(":")); assertThat(enumClass.getEnumConstants()[1].toString(), is("\u2265")); assertThat(enumClass.getEnumConstants()[2].toString(), is("<")); }
From source file:org.vulpe.view.tags.Functions.java
/** * * @param bean//w ww.j av a 2 s.c o m * @param field * @param fieldValue * @return * @throws JspException */ public static Object enumInField(final Object bean, final String field, final Object fieldValue) throws JspException { try { if (bean == null) { return null; } final String[] fieldParts = field.replace(".id", "").split("\\."); Class<?> fieldClass = null; if (fieldParts.length == 1) { fieldClass = VulpeReflectUtil.getFieldClass(bean.getClass(), fieldParts[0]); } else { int count = 1; Class<?> parentClass = bean.getClass(); for (final String fieldPart : fieldParts) { parentClass = VulpeReflectUtil.getFieldClass(parentClass, fieldPart); ++count; if (count == fieldParts.length) { fieldClass = VulpeReflectUtil.getFieldClass(parentClass, fieldParts[fieldParts.length - 1]); } } } if (fieldClass == null) { return null; } if (fieldClass.isEnum()) { for (final Object item : fieldClass.getEnumConstants()) { if (item.equals(fieldValue) || item.toString().equals(fieldValue)) { return findText(fieldClass.getName().concat(".").concat(item.toString())); } } } return null; } catch (Exception e) { throw new JspException(e); } }