java.lang.reflect.Field#isEnumConstant ( )源码实例Demo

下面列出了java.lang.reflect.Field#isEnumConstant ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: freehealth-connector   文件: JQGridParams.java
private static Criteria createEnumMask(Field field, String[] values) {
   if (field.getType().isEnum() && values != null && values.length > 0) {
      Field[] enumFlds = field.getType().getDeclaredFields();
      Field[] arr$ = enumFlds;
      int len$ = enumFlds.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Field enumField = arr$[i$];
         if (enumField.isEnumConstant() && enumField.getName().equalsIgnoreCase(values[0])) {
            Class clazz = field.getType();
            return new Criteria(field, Enum.valueOf(clazz, enumField.getName()));
         }
      }
   }

   return null;
}
 
源代码2 项目: netbeans   文件: ReflectionHelper.java
public static List<String> getEnumerationValues(String enumeration, ClassLoader loader)
        throws WebServiceReflectionException {
    try {
        List<String> enumerations = new ArrayList<String>();
        Class<?> enumerClass = Class.forName(enumeration, true, loader);

        Field[] fields = enumerClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field nextField = fields[i];
            if (nextField.isEnumConstant()) {
                enumerations.add(nextField.getName());
            }
        }

        return enumerations;
    } catch (Exception ex) {
        throw new WebServiceReflectionException(ex.getClass().getName(), ex);
    }
}
 
源代码3 项目: ews-java-api   文件: EwsUtilities.java
/**
 * Builds the schema to enum mapping dictionary.
 *
 * @param <E> Type of the enum.
 * @param c   Class
 * @return The mapping from enum to schema name
 */
private static <E extends Enum<E>> Map<String, String>
buildSchemaToEnumDict(Class<E> c) {
  Map<String, String> dict = new HashMap<String, String>();

  Field[] fields = c.getDeclaredFields();
  for (Field f : fields) {
    if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
      EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
      String fieldName = f.getName();
      String schemaName = ewsEnum.schemaName();
      if (!schemaName.isEmpty()) {
        dict.put(schemaName, fieldName);
      }
    }
  }
  return dict;
}
 
源代码4 项目: ews-java-api   文件: EwsUtilities.java
/**
 * Builds the enum dict.
 *
 * @param <E> the element type
 * @param c   the c
 * @return the map
 */
private static <E extends Enum<E>> Map<String, ExchangeVersion>
buildEnumDict(Class<E> c) {
  Map<String, ExchangeVersion> dict =
      new HashMap<String, ExchangeVersion>();
  Field[] fields = c.getDeclaredFields();
  for (Field f : fields) {
    if (f.isEnumConstant()
        && f.isAnnotationPresent(RequiredServerVersion.class)) {
      RequiredServerVersion ewsEnum = f
          .getAnnotation(RequiredServerVersion.class);
      String fieldName = f.getName();
      ExchangeVersion exchangeVersion = ewsEnum.version();
      dict.put(fieldName, exchangeVersion);
    }
  }
  return dict;
}
 
源代码5 项目: ews-java-api   文件: EwsUtilities.java
/**
 * Builds the enum to schema mapping dictionary.
 *
 * @param c class type
 * @return The mapping from enum to schema name
 */
private static Map<String, String> buildEnumToSchemaDict(Class<?> c) {
  Map<String, String> dict = new HashMap<String, String>();
  Field[] fields = c.getFields();
  for (Field f : fields) {
    if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
      EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
      String fieldName = f.getName();
      String schemaName = ewsEnum.schemaName();
      if (!schemaName.isEmpty()) {
        dict.put(fieldName, schemaName);
      }
    }
  }
  return dict;
}
 
源代码6 项目: Cangol-appcore   文件: DatabaseUtils.java
/**
 * 获取所有有效的db字段 包含父类的
 * @param clazz
 * @return
 */
public static final List<Field> getDBFields(Class clazz) {
    List<Field> fieldList = new ArrayList<>();
    Class tempClass = clazz;
    while (tempClass != null) {
        fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
        if (tempClass.getSuperclass().isAnnotationPresent(DatabaseTable.class)) {
            tempClass = tempClass.getSuperclass();
        }else{
            tempClass=null;
        }
    }
    List<Field> list = new ArrayList<>();
    for (Field field : fieldList) {
        field.setAccessible(true);
        if (field.isEnumConstant()
                || Modifier.isFinal(field.getModifiers())
                || Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        if (field.isAnnotationPresent(DatabaseField.class)) {
            list.add(field);
        }
    }
    return list;
}
 
源代码7 项目: firebase-android-sdk   文件: CustomClassMapper.java
@SuppressWarnings("unchecked")
private static <T> T deserializeToEnum(
    Object object, Class<T> clazz, DeserializeContext context) {
  if (object instanceof String) {
    String value = (String) object;
    // We cast to Class without generics here since we can't prove the bound
    // T extends Enum<T> statically

    // try to use PropertyName if exist
    Field[] enumFields = clazz.getFields();
    for (Field field : enumFields) {
      if (field.isEnumConstant()) {
        String propertyName = BeanMapper.propertyName(field);
        if (value.equals(propertyName)) {
          value = field.getName();
          break;
        }
      }
    }

    try {
      return (T) Enum.valueOf((Class) clazz, value);
    } catch (IllegalArgumentException e) {
      throw deserializeError(
          context.errorPath,
          "Could not find enum value of " + clazz.getName() + " for value \"" + value + "\"");
    }
  } else {
    throw deserializeError(
        context.errorPath,
        "Expected a String while deserializing to enum "
            + clazz
            + " but got a "
            + object.getClass());
  }
}
 
源代码8 项目: ProjectAres   文件: DocumentRegistry.java
private void registerField(Map<String, Getter> getters, Map<String, Setter> setters, Field field) {
    if(Modifier.isTransient(field.getModifiers()) ||
       Modifier.isStatic(field.getModifiers()) ||
       field.isSynthetic() ||
       field.isEnumConstant()) return;

    final String name = serializedName(field);
    final boolean gettable = !getters.containsKey(name);
    final boolean settable = !setters.containsKey(name);

    if(gettable || settable) {
        if(logger.isLoggable(Level.FINE)) {
            String access;
            if(gettable && settable) {
                access = "get/set";
            } else if(gettable) {
                access = "get";
            } else {
                access = "set";
            }
            logger.fine("  " + name + " -- " + access + " --> " + field);
        }

        if(gettable) {
            getters.put(name, new FieldGetter(this, field));
        }

        if(settable) {
            setters.put(name, new FieldSetter(this, field));
        }
    }
}
 
源代码9 项目: lams   文件: JacksonAnnotationIntrospector.java
@Override // since 2.7
public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names) {
    HashMap<String,String> expl = null;
    for (Field f : ClassUtil.getDeclaredFields(enumType)) {
        if (!f.isEnumConstant()) {
            continue;
        }
        JsonProperty prop = f.getAnnotation(JsonProperty.class);
        if (prop == null) {
            continue;
        }
        String n = prop.value();
        if (n.isEmpty()) {
            continue;
        }
        if (expl == null) {
            expl = new HashMap<String,String>();
        }
        expl.put(f.getName(), n);
    }
    // and then stitch them together if and as necessary
    if (expl != null) {
        for (int i = 0, end = enumValues.length; i < end; ++i) {
            String defName = enumValues[i].name();
            String explValue = expl.get(defName);
            if (explValue != null) {
                names[i] = explValue;
            }
        }
    }
    return names;
}
 
源代码10 项目: odata   文件: AnnotationEnumTypeFactory.java
public EnumType build(Class<?> cls) {
    EdmEnum enumAnno = cls.getAnnotation(EdmEnum.class);

    boolean isFlags = enumAnno.flags();

    // NOTE: Values are generated automatically. If isFlags is false, then consecutive integer values starting
    // from 0 are used (0, 1, 2, ...). If isFlags is true, then consecutive bits are used (1, 2, 4, 8, ...).

    List<EnumMember> members = new ArrayList<>();
    long value = isFlags ? 1L : 0L;
    for (Field field : cls.getDeclaredFields()) {
        if (field.isEnumConstant()) {
            members.add(new EnumMemberImpl(field.getName(), value));
            if (isFlags) {
                value <<= 1;
            } else {
                value++;
            }
        }
    }

    return new EnumTypeImpl.Builder()
            .setName(getTypeName(enumAnno, cls))
            .setNamespace(getNamespace(enumAnno, cls))
            .setJavaType(cls)
            .setUnderlyingType(enumAnno.underlyingType())
            .setIsFlags(isFlags)
            .addMembers(members)
            .build();
}
 
源代码11 项目: Cangol-appcore   文件: DatabaseUtils.java
/**
 * 创建表索引
 *
 * @param db
 * @param clazz
 */
public static void createIndex(SQLiteDatabase db, Class<?> clazz, String indexName, String... fieldNames) {
    if (clazz.isAnnotationPresent(DatabaseTable.class)) {
        final DatabaseTable table = clazz.getAnnotation(DatabaseTable.class);
        final String tableName = "".equals(table.value()) ? clazz.getSimpleName() : table.value();
        final StringBuilder sql = new StringBuilder("CREATE INDEX ");
        sql.append(indexName).append(" on ").append(tableName).append('(');
        Field field = null;
        String columnName = null;
        for (int i = 0; i < fieldNames.length; i++) {
            try {
                field = clazz.getDeclaredField(fieldNames[i]);
                field.setAccessible(true);
                if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
                    continue;
                } else if (field.isAnnotationPresent(DatabaseField.class)) {
                    final DatabaseField dbField = field.getAnnotation(DatabaseField.class);
                    columnName = "".equals(dbField.value()) ? field.getName() : dbField.value();
                    sql.append(columnName);
                    if (i < fieldNames.length - 1)
                        sql.append(',');
                }
            } catch (NoSuchFieldException e) {
                Log.e(e.getMessage());
            }
        }
        sql.append(')');
        db.execSQL(sql.toString());
    } else {
        throw new IllegalStateException(clazz + " not DatabaseTable Annotation");
    }
}
 
源代码12 项目: ldp4j   文件: ClassDescription.java
@Override
protected void processType(Field type) {
	super.addTitle("Field");
	super.addBlockField("member", wrapElementAs(type,Member.class));
	super.addBlockField("annotated element", wrapElementAs(type,AnnotatedElement.class));
	super.addField("accessible", type.isAccessible());
	super.addField("type", type.getType());
	super.addField("generic type", type.getGenericType());
	super.addField("enum constant", type.isEnumConstant());
}
 
源代码13 项目: opt4j   文件: Format.java
/**
 * Returns the formatted (html) tooltip of a {@link Property}.
 * 
 * @param property
 *            the property
 * @return the tooltip
 */
public String getTooltip(Property property) {
	String text = "<html><b>" + getName(property) + "</b>";
	String info = property.getInfo();
	if (info != null) {
		text += xmlBreak + info;
	}
	if (property.getType().isEnum()) {
		Class<?> type = property.getType();
		text += xmlBreak;

		Field[] fields = type.getDeclaredFields();
		for (Field field : fields) {
			if (field.isEnumConstant()) {
				String name = field.getName();
				Icon icon = field.getAnnotation(Icon.class);
				Info i = field.getAnnotation(Info.class);
				text += "&nbsp;" + name;
				if (icon != null || i != null) {
					text += " - ";
				}
				if (icon != null) {
					text += "<img src=\"" + Icons.getURL(icon.value()) + "\">";

					System.out.println(text + " " + icon.value());
				}
				if (i != null) {
					text += i.value();
				}

				Citation c = field.getAnnotation(Citation.class);
				if (c != null)
					text += "&nbsp;&nbsp;<span style='color: gray;'>[" + formatIEEE(c) + "]</span>";
				text += xmlBreak;
			}
		}
	}

	text += "</html>";

	return text;
}
 
源代码14 项目: lua-for-android   文件: ClassReader.java
public static long getMemberFlag(Field field){
    int flag=field.getModifiers();
    if(field.isSynthetic()) flag|=SYNTHETIC;
    if(field.isEnumConstant()) flag|=ENUM;
    return flag;
}
 
源代码15 项目: lams   文件: AnnotationMapper.java
private void processTypes(final Set<Class<?>> types) {
    while (!types.isEmpty()) {
        final Iterator<Class<?>> iter = types.iterator();
        final Class<?> type = iter.next();
        iter.remove();

        synchronized(type) {
            if (annotatedTypes.contains(type)) {
                continue;
            }
            try {
                if (type.isPrimitive()) {
                    continue;
                }

                addParametrizedTypes(type, types);

                processConverterAnnotations(type);
                processAliasAnnotation(type, types);
                processAliasTypeAnnotation(type);

                if (type.isInterface()) {
                    continue;
                }

                processImplicitCollectionAnnotation(type);

                final Field[] fields = type.getDeclaredFields();
                for (int i = 0; i < fields.length; i++ ) {
                    final Field field = fields[i];
                    if (field.isEnumConstant()
                        || (field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) > 0) {
                        continue;
                    }

                    addParametrizedTypes(field.getGenericType(), types);

                    if (field.isSynthetic()) {
                        continue;
                    }

                    processFieldAliasAnnotation(field);
                    processAsAttributeAnnotation(field);
                    processImplicitAnnotation(field);
                    processOmitFieldAnnotation(field);
                    processLocalConverterAnnotation(field);
                }
            } finally {
                annotatedTypes.add(type);
            }
        }
    }
}
 
源代码16 项目: Cangol-appcore   文件: JsonUtils.java
public static <T> T parserToObject(Class<T> c, JSONObject jsonObject, boolean useAnnotation,boolean excludeTransient) throws JSONParserException {
    if (jsonObject == null) {
        return null;
    }
    T t = null;
    try {
        final Map<String, Class> typeMap = new HashMap<>();
        final Constructor constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        t = (T) constructor.newInstance();
        final Field[] fields = c.getDeclaredFields();
        String filedName = null;
        for (final Field field : fields) {
            field.setAccessible(true);
            if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers()) ) {
                continue;
            }
            if(excludeTransient&&Modifier.isTransient(field.getModifiers())){
                continue;
            }
            filedName = getFieldName(field, useAnnotation);
            if (!List.class.isAssignableFrom(field.getType())) {
                Class<?> filedClass = null;

                if (field.getGenericType() instanceof TypeVariable) {
                    final TypeVariable aType = (TypeVariable) field.getGenericType();
                    filedClass = typeMap.get(aType.getName());
                } else {
                    filedClass = field.getType();
                }
                if (jsonObject.has(filedName))
                    field.set(t, getValueFromJson(t, filedClass, filedName, jsonObject, useAnnotation));
            } else {
                if (field.getGenericType() instanceof ParameterizedType) {
                    final ParameterizedType pt = (ParameterizedType) field.getGenericType();
                    final Class<?> genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
                    final List<?> list = parserToList(genericClazz, getJSONArray(jsonObject, filedName), useAnnotation);
                    field.set(t, list);
                } else {
                    Log.i(TAG, field.getName() + " require have generic");
                }
            }
        }
    } catch (Exception e) {
        throw new JSONParserException(c, "constructor is not accessible,must have zero-argument constructor", e);
    }
    return t;
}
 
源代码17 项目: gvnix   文件: QuerydslUtils.java
/**
 * Return where clause expression for non-String
 * {@code entityPath.fieldName} by transforming it to text before check its
 * value.
 * <p/>
 * Expr:
 * {@code entityPath.fieldName.as(String.class) like ('%' + searchStr + '%')}
 * <p/>
 * Like operation is case insensitive.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @param enumClass Enumeration type. Needed to enumeration values
 * @return BooleanExpression
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> BooleanExpression createEnumExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr,
        Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}
 
源代码18 项目: gvnix   文件: QuerydslUtilsBeanImpl.java
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> BooleanExpression createEnumExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr,
        Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}
 
源代码19 项目: Cangol-appcore   文件: XmlUtils.java
private static void toXml(XmlSerializer serializer, Object obj, boolean useAnnotation) {
    try {
        serializer.startTag(null, obj.getClass().getSimpleName());
        final Field[] fields = obj.getClass().getDeclaredFields();
        for (final Field field : fields) {
            field.setAccessible(true);
            if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
           final String filedName = getFieldName(field, useAnnotation);
            if (!List.class.isAssignableFrom(field.getType())) {
                //非集合类型
                if (isBaseClass(field.getType())) {
                    if (field.isAnnotationPresent(Attribute.class)) {
                        serializer.attribute(null, filedName, String.valueOf(field.get(obj) == null ? "" : field.get(obj)));
                    } else {
                        serializer.startTag(null, filedName);
                        serializer.text(String.valueOf(field.get(obj) == null ? "" : field.get(obj)));
                        serializer.endTag(null, filedName);
                    }
                } else {
                    toXml(serializer, field.get(obj), useAnnotation);
                }
            } else {
                //集合类型
                if (field.getGenericType() instanceof ParameterizedType) {
                    final List<?> list = (List<?>) field.get(obj);
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            toXml(serializer, list.get(i), useAnnotation);
                        }
                    }
                } else {
                    Log.i(TAG, field.getName() + " require have generic");
                }
            }
        }
        serializer.endTag(null, obj.getClass().getSimpleName());
    } catch (Exception e) {
        Log.d(TAG, e.getMessage());
    }
}
 
源代码20 项目: Cangol-appcore   文件: JsonUtils.java
public static <T> JSONObject toJSONObject(T obj, boolean useAnnotation,boolean excludeTransient) {
    if (obj == null) {
        return null;
    }
    if (List.class.isAssignableFrom(obj.getClass())) {
        return null;
    }

    final JSONObject json = new JSONObject();
    final Field[] fields = obj.getClass().getDeclaredFields();
    try {
        for (final Field field : fields) {
            field.setAccessible(true);
            if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            if(excludeTransient&&Modifier.isTransient(field.getModifiers())){
                continue;
            }

            final String filedName = getFieldName(field, useAnnotation);
            if (!List.class.isAssignableFrom(field.getType())) {
                //非集合类型
                if (isBaseClass(field.getType())) {
                    json.put(filedName, field.get(obj));
                } else {
                    json.put(filedName, toJSONObject(field.get(obj), useAnnotation));
                }
            } else {
                //集合类型
                if (field.getGenericType() instanceof ParameterizedType) {
                    final List<?> list = (List<?>) field.get(obj);
                    final JSONArray jsonArray = new JSONArray();
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            if (isBaseClass(list.get(i).getClass())) {
                                jsonArray.put(list.get(i));
                            } else {
                                jsonArray.put(toJSONObject(list.get(i), useAnnotation));
                            }
                        }
                    }
                    json.put(filedName, jsonArray);
                } else {
                    Log.d(TAG, field.getName() + " require have generic");
                }
            }

        }
    } catch (Exception e) {
        Log.d(TAG, e.getMessage());
    }
    return json;
}