List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:nc.noumea.mairie.appock.core.services.impl.BootstrapServiceImpl.java
@SuppressWarnings("unchecked") void checkConcordanceEnum(Class<?> classeEnum, String nomTable) { String requete = "SELECT name FROM " + nomTable + " ORDER BY ID"; List<String> listeName = em.createNativeQuery(requete).getResultList(); if (listeName.size() != ((Class<Enum<?>>) classeEnum).getEnumConstants().length) { throw new RuntimeException("L'enumration " + classeEnum.getSimpleName() + " ne contient pas le mme nombre d'lments que dans la table " + nomTable); }//from www. j av a 2 s. c o m Object[] enumConstants = classeEnum.getEnumConstants(); for (int i = 0; i < listeName.size(); i++) { String name = listeName.get(i); try { @SuppressWarnings("rawtypes") Enum enumValue = Enum.valueOf((Class<Enum>) classeEnum, name); if (enumValue != enumConstants[i]) { throw new RuntimeException("L'enumration " + classeEnum.getSimpleName() + " la position " + i + " ne vaut pas la valeur attendue " + name); } } catch (IllegalArgumentException e) { throw new RuntimeException("L'enumration " + classeEnum.getSimpleName() + " ne contient pas la valeur '" + name + "' prsente dans la table " + nomTable); } } }
From source file:org.tango.server.attribute.ReflectAttributeBehavior.java
@Override public void setValue(final AttributeValue value) throws DevFailed { if (setter != null && setter.getParameterTypes().length == 1) { final Class<?> paramSetter = getParamSetter(); try {/*from w ww .j av a2 s . c o m*/ if (paramSetter.equals(DeviceState.class)) { setter.invoke(businessObject, DeviceState.getDeviceState((DevState) value.getValue())); } else if (Enum.class.isAssignableFrom(paramSetter)) { final short enumValue = (Short) value.getValue(); setter.invoke(businessObject, paramSetter.getEnumConstants()[enumValue]); } else if (paramSetter.equals(DeviceState[].class)) { final DevState[] states = (DevState[]) value.getValue(); final DeviceState[] devStates = new DeviceState[states.length]; for (int i = 0; i < devStates.length; i++) { devStates[i] = DeviceState.getDeviceState(states[i]); } setter.invoke(businessObject, (Object) devStates); } else { final Class<?> input = getInputClass(value); checkParamTypes(value, paramSetter, input); setter.invoke(businessObject, value.getValue()); } } catch (final IllegalArgumentException e) { DevFailedUtils.throwDevFailed(e); } catch (final IllegalAccessException e) { DevFailedUtils.throwDevFailed(e); } catch (final InvocationTargetException e) { throwDevFailed(e); } } }
From source file:com.haulmont.cuba.desktop.gui.components.DesktopAbstractOptionsField.java
@Override public void setDatasource(Datasource datasource, String property) { this.datasource = datasource; if (datasource == null) { setValue(null);//from ww w . ja v a2 s . c o m return; } MetaClass metaClass = datasource.getMetaClass(); resolveMetaPropertyPath(metaClass, property); itemChangeListener = e -> { if (updatingInstance) return; Object value = InstanceUtils.getValueEx(e.getItem(), metaPropertyPath.getPath()); updateComponent(value); fireChangeListeners(value); }; // noinspection unchecked datasource.addItemChangeListener(new WeakItemChangeListener(datasource, itemChangeListener)); itemPropertyChangeListener = e -> { if (updatingInstance) return; if (e.getProperty().equals(metaPropertyPath.toString())) { updateComponent(e.getValue()); fireChangeListeners(e.getValue()); } }; // noinspection unchecked datasource.addItemPropertyChangeListener( new WeakItemPropertyChangeListener(datasource, itemPropertyChangeListener)); initRequired(metaPropertyPath); if (metaProperty.getRange().isEnum()) { Enumeration enumeration = metaProperty.getRange().asEnumeration(); @SuppressWarnings("unchecked") Class<Enum> javaClass = enumeration.getJavaClass(); setOptionsList(Arrays.asList(javaClass.getEnumConstants())); setCaptionMode(CaptionMode.ITEM); } if (DynamicAttributesUtils.isDynamicAttribute(metaProperty)) { CategoryAttribute categoryAttribute = DynamicAttributesUtils.getCategoryAttribute(metaProperty); if (categoryAttribute != null && categoryAttribute.getDataType() == PropertyType.ENUMERATION) { setOptionsMap(categoryAttribute.getLocalizedEnumerationMap()); } } if ((datasource.getState() == Datasource.State.VALID) && (datasource.getItem() != null)) { Object newValue = InstanceUtils.getValueEx(datasource.getItem(), metaPropertyPath.getPath()); updateComponent(newValue); fireChangeListeners(newValue); } if (metaProperty.isReadOnly()) { setEditable(false); } handleFilteredAttributes(this, this.datasource, metaPropertyPath); securityItemChangeListener = e -> handleFilteredAttributes(this, this.datasource, metaPropertyPath); // noinspection unchecked this.datasource .addItemChangeListener(new WeakItemChangeListener(this.datasource, securityItemChangeListener)); initBeanValidator(); }
From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java
@SuppressWarnings("rawtypes") protected Enum getEnum(Class clazz, String string) throws Exception { if (!clazz.isEnum()) throw new Exception("Class " + clazz.getName() + " is not an enum."); for (Object constant : clazz.getEnumConstants()) { if (((Enum) constant).toString().equals(string)) { return (Enum) constant; }//ww w. j av a 2s . c o m } throw new Exception("String " + string + " not a valid enum constant for " + clazz.getName()); }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapComplexTypes(List<APITypeModel> typeModels, Field fields[], boolean onlyConsumeField) { //Should strip duplicate types Set<String> typesInList = new HashSet<>(); typeModels.forEach(type -> {//from w w w .j a v a 2 s.c o m typesInList.add(type.getName()); }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); for (Field field : fields) { boolean capture = true; if (onlyConsumeField) { ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consumeField == null) { capture = false; } } if (capture) { Class fieldClass = field.getType(); DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { fieldClass = dataType.value(); } if (ReflectionUtil.isComplexClass(fieldClass)) { APITypeModel typeModel = new APITypeModel(); typeModel.setName(fieldClass.getSimpleName()); APIDescription aPIDescription = (APIDescription) fieldClass.getAnnotation(APIDescription.class); if (aPIDescription != null) { typeModel.setDescription(aPIDescription.value()); } Set<String> fieldList = mapValueField(typeModel.getFields(), fieldClass.getDeclaredFields(), onlyConsumeField); if (fieldClass.isEnum()) { typeModel.setObject(Arrays.toString(fieldClass.getEnumConstants())); } else { if (fieldClass.isInterface() == false) { try { typeModel.setObject(objectMapper.writeValueAsString(fieldClass.newInstance())); String cleanUpJson = StringProcessor.stripeFieldJSON(typeModel.getObject(), fieldList); typeModel.setObject(cleanUpJson); } catch (InstantiationException | IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, "Unable to process/map complex field: " + fieldClass.getSimpleName(), ex); typeModel.setObject("{ Unable to view }"); } mapComplexTypes(typeModels, fieldClass.getDeclaredFields(), onlyConsumeField); } } typeModels.add(typeModel); typesInList.add(typeModel.getName()); } } } }
From source file:com.grepcurl.random.ObjectGenerator.java
public <T> T generate(Class<T> klass) { Validate.notNull(klass);//from www . j a va2 s . c o m if (verbose) { log(String.format("generating object of type: %s", klass)); } try { Deque<Object> objectStack = new ArrayDeque<>(); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor().newInstance(); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, null, t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { throw new FailedRandomObjectGenerationException(e); } }
From source file:de.escalon.hypermedia.action.ActionInputParameter.java
public Object[] getPossibleValues(ActionDescriptor actionDescriptor) { try {/*from w w w .ja v a2 s .c om*/ Class<?> parameterType = getParameterType(); 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> options = select.options(); Options instance = options.newInstance(); List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getCallValue()); } } Object[] args = from.toArray(); possibleValues = instance.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.escalon.hypermedia.action.ActionInputParameter.java
public Object[] getPossibleValues(Property property, ActionDescriptor actionDescriptor) { // TODO remove code duplication of getPossibleValues try {// w w w. j a va 2s.com Class<?> parameterType = property.getType(); 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(property, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Annotation[][] parameterAnnotations = property.getWriteMethod().getParameterAnnotations(); // setter has exactly one param Select select = getSelectAnnotationFromFirstParam(parameterAnnotations[0]); 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.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.github.reinert.jjschema.JsonSchemaGenerator.java
private <T> void processEnum(Class<T> type, ObjectNode schema) { ArrayNode enumArray = schema.putArray("enum"); for (T constant : type.getEnumConstants()) { String value = constant.toString(); // Check if value is numeric try {// ww w .ja va 2s.c o m // First verifies if it is an integer Long integer = Long.parseLong(value); enumArray.add(integer); } // If not then verifies if it is an floating point number catch (NumberFormatException e) { try { BigDecimal number = new BigDecimal(value); enumArray.add(number); } // Otherwise add as String catch (NumberFormatException e1) { enumArray.add(value); } } } }
From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static Object genTypeValue(Type type) { Object ret = typeValueCache.get(type); if (ret != null) { return ret; }//from w ww .j av a 2 s .co m // only use positive primitive values if (type.equals(boolean.class)) { return rand.nextBoolean(); } else if (type.equals(byte.class)) { return bytes[rand.nextInt(4)]; } else if (type.equals(int.class)) { return rand.nextInt(1000000); } else if (type.equals(long.class)) { return Long.valueOf(rand.nextInt(1000000)); } else if (type.equals(float.class)) { return rand.nextFloat(); } else if (type.equals(double.class)) { return rand.nextDouble(); } else if (type.equals(String.class)) { return String.format("%c%c%c", 'a' + rand.nextInt(26), 'a' + rand.nextInt(26), 'a' + rand.nextInt(26)); } else if (type instanceof Class) { Class clazz = (Class) type; if (clazz.isArray()) { Class compClass = clazz.getComponentType(); if (compClass != null) { ret = Array.newInstance(compClass, 2); Array.set(ret, 0, genTypeValue(compClass)); Array.set(ret, 1, genTypeValue(compClass)); } } else if (clazz.isEnum()) { Object[] values = clazz.getEnumConstants(); ret = values[rand.nextInt(values.length)]; } else if (clazz.equals(ByteBuffer.class)) { // return new ByteBuffer every time // to prevent potential side effects ByteBuffer buff = ByteBuffer.allocate(4); rand.nextBytes(buff.array()); return buff; } } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type rawType = pt.getRawType(); Type[] params = pt.getActualTypeArguments(); // only support EnumSet<T>, List<T>, Set<T>, Map<K,V> if (rawType.equals(EnumSet.class)) { if (params[0] instanceof Class) { Class c = (Class) (params[0]); return EnumSet.allOf(c); } } if (rawType.equals(List.class)) { ret = Lists.newArrayList(genTypeValue(params[0])); } else if (rawType.equals(Set.class)) { ret = Sets.newHashSet(genTypeValue(params[0])); } else if (rawType.equals(Map.class)) { Map<Object, Object> map = Maps.newHashMap(); map.put(genTypeValue(params[0]), genTypeValue(params[1])); ret = map; } } if (ret == null) { throw new IllegalArgumentException("type " + type + " is not supported"); } typeValueCache.put(type, ret); return ret; }