List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:com.github.gekoh.yagen.ddl.TableConfig.java
private void gatherEnumCheckConstraints(final Map<String, String> attr2colName, final String attrPath, Class type) {/*from www . j ava2 s . c om*/ // HACK: we are using field annotations, need to skip methods otherwise we would have wrong constraints traverseFieldsAndMethods(type, true, false, new GatherFieldOrMethodInfoAction() { @Override public void gatherInfo(AccessibleObject fOm) { String attributeName = getAttributeName(fOm); String attrPathField = attrPath + "." + attributeName; Class attributeType = getAttributeType(fOm); if (fOm.isAnnotationPresent(Embedded.class)) { addAttributeOverrides(attr2colName, attrPathField, fOm); gatherEnumCheckConstraints(attr2colName, attrPathField, attributeType); } else if (attributeType.isEnum()) { String colName = attr2colName.get(attrPathField); if (colName == null) { if (fOm.isAnnotationPresent(Column.class)) { colName = getIdentifierForReference(fOm.getAnnotation(Column.class).name()); } if (StringUtils.isEmpty(colName)) { colName = getIdentifierForReference(attributeName); } } boolean useName = fOm.isAnnotationPresent(Enumerated.class) && fOm.getAnnotation(Enumerated.class).value() == EnumType.STRING; StringBuilder cons = new StringBuilder(); for (Object e : attributeType.getEnumConstants()) { if (cons.length() > 0) { cons.append(", "); } if (useName) { cons.append("'").append(((Enum) e).name()).append("'"); } else { cons.append(((Enum) e).ordinal()); } } columnNameToEnumCheckConstraints.put(colName, cons.toString()); } } }); Class superClass = getEntitySuperclass(type); if (superClass != null) { gatherEnumCheckConstraints(attr2colName, attrPath, superClass); } }
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 {/*from w ww .j av a 2 s .com*/ 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:com.britesnow.snow.web.RequestContext.java
/** * Return the param value as "cls" class object. If the value is null (or empty string) return the defaultValue.<br> * /*from w w w . java 2 s . c om*/ * Note: For the first call, this method will parse the request (in case of a multipart).<br /> * * <div class="issues"> <strong>Issues</strong> * <ul> * <li>FIXME: Need to fix the multipart handling. Can be simplified</li> * </ul> * </div> * * @param <T> * Class of the return element * @param name * of the parameter * @param cls * Class of the return element * @param defaultValue * Default value in case of an error or null/empty value * @return */ @SuppressWarnings("unchecked") public <T> T getParamAs(String name, Class<T> cls, T defaultValue) { Map<String, Object> paramMap = getParamMap(); if (paramMap == null) { return defaultValue; } // if we have a primitive type or array, then, just get the single value and convert it to the appropriate type if (ObjectUtil.isPrimitive(cls) || cls.isArray() || cls == FileItem.class || cls.isEnum()) { // first, try to get it from the paramMap Object valueObject = paramMap.get(name); if (isMultipart) { // HACK // if not found, try to get it from the regular HttpServletRequest // (in the case of a multiPart post, // HttpServletRequest.getParameter still have the URL params) if (valueObject == null) { valueObject = getReq().getParameter(name); } } if (valueObject == null) { return defaultValue; } else if (valueObject instanceof String) { return (T) ObjectUtil.getValue((String) valueObject, cls, defaultValue); } else if (valueObject instanceof String[]) { return (T) ObjectUtil.getValue((String[]) valueObject, cls, defaultValue); } else { // hope for the best (should be a fileItem) return (T) valueObject; } } // otherwise, if it is not a primitive type, attempt to create the targeted object with the corresponding // paramMap else { Map subParamMap = getParamMap(name + "."); // i.e., "product." if (subParamMap != null) { try { T value = cls.newInstance(); ObjectUtil.populate(value, subParamMap); return value; } catch (Exception e) { logger.warn(e.getMessage()); return defaultValue; } } else { return defaultValue; } } }
From source file:org.tdar.core.service.ReflectionService.java
/** * Cast the value to the object type of the field and call the setter. Validate the propert in the process. * // w w w .j av a 2 s .c o m * @param beanToProcess * @param name * @param value */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void validateAndSetProperty(Object beanToProcess, String name, String value) { List<String> errorValueList = Arrays.asList(name, value); try { logger.trace("processing: {} - {} --> {}", beanToProcess, name, value); Class propertyType = PropertyUtils.getPropertyType(beanToProcess, name); // handle types should we be testing column length? if (propertyType.isEnum()) { try { BeanUtils.setProperty(beanToProcess, name, Enum.valueOf(propertyType, value)); } catch (IllegalArgumentException e) { logger.debug("cannot set property:", e); throw new TdarRecoverableRuntimeException("reflectionService.not_valid_value", e, errorValueList); } } else { if (Integer.class.isAssignableFrom(propertyType)) { try { Double dbl = Double.valueOf(value); if (dbl == Math.floor(dbl)) { value = new Integer((int) Math.floor(dbl)).toString(); } } catch (NumberFormatException nfe) { throw new TdarRecoverableRuntimeException("reflectionService.expecting_integer", errorValueList); } } if (Long.class.isAssignableFrom(propertyType)) { try { Double dbl = Double.valueOf(value); if (dbl == Math.floor(dbl)) { value = new Long((long) Math.floor(dbl)).toString(); } } catch (NumberFormatException nfe) { throw new TdarRecoverableRuntimeException("reflectionService.expecting_big_integer", errorValueList); } } if (Float.class.isAssignableFrom(propertyType)) { try { Float.parseFloat(value); } catch (NumberFormatException nfe) { throw new TdarRecoverableRuntimeException("reflectionService.expecting_floating_point", errorValueList); } } BeanUtils.setProperty(beanToProcess, name, value); } } catch (Exception e1) { if (e1 instanceof TdarRecoverableRuntimeException) { throw (TdarRecoverableRuntimeException) e1; } logger.debug("error processing bulk upload: {}", e1); throw new TdarRecoverableRuntimeException("reflectionService.expecting_generic", errorValueList); } }
From source file:com.sunchenbin.store.feilong.core.lang.ClassUtil.java
/** * class info map for LOGGER.//from w w w. ja v a 2s. co m * * @param klass * the clz * @return the map for log */ public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) { if (Validator.isNullOrEmpty(klass)) { return Collections.emptyMap(); } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.sunchenbin.store.feilong.core.date.DatePattern" map.put("clz.getName()", klass.getName());//"com.sunchenbin.store.feilong.core.date.DatePattern" map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern" map.put("clz.getComponentType()", klass.getComponentType()); // ?? ,voidboolean?byte?char?short?int?long?float double? map.put("clz.isPrimitive()", klass.isPrimitive()); // ??, map.put("clz.isLocalClass()", klass.isLocalClass()); // ????,?,????? map.put("clz.isMemberClass()", klass.isMemberClass()); //isSynthetic()?Class????java??false,?true,JVM???,java?????? map.put("clz.isSynthetic()", klass.isSynthetic()); map.put("clz.isArray()", klass.isArray()); map.put("clz.isAnnotation()", klass.isAnnotation()); //??true map.put("clz.isAnonymousClass()", klass.isAnonymousClass()); map.put("clz.isEnum()", klass.isEnum()); return map; }
From source file:org.apache.syncope.console.pages.ReportletConfModalPage.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private FieldPanel buildSinglePanel(final Class<?> type, final String fieldName, final String id) { FieldPanel result = null;//from w w w.ja va2 s .c o m PropertyModel model = new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName); if (ClassUtils.isAssignable(Boolean.class, type)) { result = new AjaxCheckBoxPanel(id, fieldName, model); } else if (ClassUtils.isAssignable(Number.class, type)) { result = new SpinnerFieldPanel<Number>(id, fieldName, (Class<Number>) type, model, null, null); } else if (Date.class.equals(type)) { result = new DateTimeFieldPanel(id, fieldName, model, SyncopeConstants.DEFAULT_DATE_PATTERN); } else if (type.isEnum()) { result = new AjaxDropDownChoicePanel(id, fieldName, model) .setChoices(Arrays.asList(type.getEnumConstants())); } // treat as String if nothing matched above if (result == null) { result = new AjaxTextFieldPanel(id, fieldName, model); } return result; }
From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java
protected MetadataObjectInfo<Range> loadRange(MetaProperty metaProperty, Class<?> type, Map<String, Object> map) { Datatype datatype = (Datatype) map.get("datatype"); if (datatype != null) { // A datatype is assigned explicitly return new MetadataObjectInfo<>(new DatatypeRange(datatype)); }//w w w . j a va2 s . c om datatype = getAdaptiveDatatype(metaProperty, type); if (datatype == null) { datatype = datatypes.get(type); } if (datatype != null) { MetaClass metaClass = metaProperty.getDomain(); Class javaClass = metaClass.getJavaClass(); try { String name = "get" + StringUtils.capitalize(metaProperty.getName()); Method method = javaClass.getMethod(name); Class<Enum> returnType = (Class<Enum>) method.getReturnType(); if (returnType.isEnum()) { return new MetadataObjectInfo<>(new EnumerationRange(new EnumerationImpl<>(returnType))); } } catch (NoSuchMethodException e) { // ignore } return new MetadataObjectInfo<>(new DatatypeRange(datatype)); } else if (type.isEnum()) { return new MetadataObjectInfo<>(new EnumerationRange(new EnumerationImpl(type))); } else { return new MetadataObjectInfo<>(null, Collections.singletonList(new RangeInitTask(metaProperty, type, map))); } }
From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java
/** * Checks all of the classes in the serialization scope that implement * TetradSerializable to make sure all of their fields are either themselves * (a) primitive, (b) TetradSerializable, or (c) assignable from types * designated as safely serializable by virtue of being included in the * safelySerializableTypes array (see), or are arrays whose lowest order * component types satisfy either (a), (b), or (c). Safely serializable * classes in the Java API currently include collections classes, plus * String and Class. Collections classes are included, since their types * will be syntactically checkable in JDK 1.5. String and Class are members * of a broader type of Class whose safely can by checked by making sure * there is no way to pass into them via constructor or method argument any * object that is not TetradSerializable or safely serializable. But it's * easy enough now to just make a list.//from www . jav a 2s. c o m * * @see #safelySerializableTypes */ public void checkNestingOfFields() { List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class); boolean foundUnsafeField = false; for (Object aClass : classes) { Class clazz = (Class) aClass; if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) { continue; } Field[] fields = clazz.getDeclaredFields(); FIELDS: for (Field field : fields) { // System.out.println(field); if (Modifier.isTransient(field.getModifiers())) { continue; } if (Modifier.isStatic(field.getModifiers())) { continue; } Class type = field.getType(); while (type.isArray()) { type = type.getComponentType(); } if (type.isPrimitive()) { continue; } if (type.isEnum()) { continue; } // // Printing out Collections fields temporarily. // if (Collection.class.isAssignableFrom(type)) { // System.out.println("COLLECTION FIELD: " + field); // } // // if (Map.class.isAssignableFrom(type)) { // System.out.println("MAP FIELD: " + field); // } if (TetradSerializable.class.isAssignableFrom(type) && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) { continue; } for (Class safelySerializableClass : safelySerializableTypes) { if (safelySerializableClass.isAssignableFrom(type)) { continue FIELDS; } } // A reference in an inner class to the outer class. if (field.getName().equals("this$0")) { continue; } System.out.println("UNSAFE FIELD:" + field); foundUnsafeField = true; } } if (foundUnsafeField) { throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately."); } }
From source file:org.snowfk.web.RequestContext.java
/** * Return the param value as "cls" class object. If the value is null (or * empty string) return the defaultValue.<br> * /*from www . j av a2s . co m*/ * Note: For the first call, this method will parse the request (in case of * a multipart).<br /> * * <div class="issues"> <strong>Issues</strong> * <ul> * <li>FIXME: Need to fix the multipart handling. Can be simplified</li> * </ul> * </div> * * @param <T> * Class of the return element * @param name * of the parameter * @param cls * Class of the return element * @param defaultValue * Default value in case of an error or null/empty value * @return */ @SuppressWarnings("unchecked") public <T> T getParam(String name, Class<T> cls, T defaultValue) { Map<String, Object> paramMap = getParamMap(); if (paramMap == null) { return defaultValue; } //if we have a primitive type or array, then, just get the single value and convert it to the appropriate type if (ObjectUtil.isPrimitive(cls) || cls.isArray() || cls == FileItem.class || cls.isEnum()) { // first, try to get it from the paramMap Object valueObject = paramMap.get(name); if (isMultipart) { // HACK // if not found, try to get it from the regular HttpServletRequest // (in the case of a multiPart post, // HttpServletRequest.getParameter still have the URL params) if (valueObject == null) { valueObject = getReq().getParameter(name); } } if (valueObject == null) { return defaultValue; } else if (valueObject instanceof String) { return (T) ObjectUtil.getValue((String) valueObject, cls, defaultValue); } else if (valueObject instanceof String[]) { return (T) ObjectUtil.getValue((String[]) valueObject, cls, defaultValue); } else { //hope for the best (should be a fileItem) return (T) valueObject; } } //otherwise, if it is not a primitive type, attempt to create the targeted object with the corresponding paramMap else { Map subParamMap = getParamMap(name + "."); // i.e., "product." if (subParamMap != null) { try { T value = cls.newInstance(); ObjectUtil.populate(value, subParamMap); return value; } catch (Exception e) { logger.warn(e.getMessage()); return defaultValue; } } else { return defaultValue; } } }
From source file:com.l2jserver.service.database.orientdb.AbstractOrientDatabaseService.java
/** * Returns the {@link OType} representing the type represented by * {@link Class}//from w ww . ja v a 2s . c o m * * @param cls * the class * @return the {@link OType}. Never null. */ private OType getType(Class<?> cls) { if (cls.isEnum()) { return OType.STRING; } else if (ClassUtils.isSubclass(cls, Date.class)) { return OType.DATETIME; } else { return OType.getTypeByClass(cls); } }