下面列出了java.lang.reflect.Field#isEnumConstant ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 获取所有有效的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;
}
@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());
}
}
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));
}
}
}
@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;
}
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();
}
/**
* 创建表索引
*
* @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");
}
}
@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());
}
/**
* 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 += " " + 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 += " <span style='color: gray;'>[" + formatIEEE(c) + "]</span>";
text += xmlBreak;
}
}
}
text += "</html>";
return text;
}
public static long getMemberFlag(Field field){
int flag=field.getModifiers();
if(field.isSynthetic()) flag|=SYNTHETIC;
if(field.isEnumConstant()) flag|=ENUM;
return flag;
}
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);
}
}
}
}
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;
}
/**
* 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;
}
/**
* {@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;
}
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());
}
}
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;
}