Java Code Examples for java.lang.reflect.Field#getAnnotation()

The following examples show how to use java.lang.reflect.Field#getAnnotation() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: butterknife   File: ButterKnife.java    License: Apache License 2.0 6 votes vote down vote up
private static @Nullable Unbinder parseBindView(Object target, Field field, View source) {
  BindView bindView = field.getAnnotation(BindView.class);
  if (bindView == null) {
    return null;
  }
  validateMember(field);

  int id = bindView.value();
  Class<?> viewClass = field.getType();
  if (!View.class.isAssignableFrom(viewClass) && !viewClass.isInterface()) {
    throw new IllegalStateException(
        "@BindView fields must extend from View or be an interface. ("
            + field.getDeclaringClass().getName()
            + '.'
            + field.getName()
            + ')');
  }

  String who = "field '" + field.getName() + "'";
  Object view = Utils.findOptionalViewAsType(source, id, who, viewClass);
  trySet(field, target, view);

  return new FieldUnbinder(target, field);
}
 
Example 2
Source Project: grouter-android   File: RouterInject.java    License: Apache License 2.0 6 votes vote down vote up
public static void inject(Object targetObject, Bundle extras, Uri uri) throws Exception {
    SafeBundle bundle = new SafeBundle(extras, uri);
    Class clazz = targetObject.getClass();
    List<Field> fields = getDeclaredFields(clazz);
    for (Field field : fields) {
        RouterField annotation = field.getAnnotation(RouterField.class);
        if (annotation == null) {
            continue;
        }
        // 解析注解中的名称
        String name = annotation.value();
        if (name.length() != 0 && bundle.containsKey(name)) {
            assignment(targetObject, field, name, bundle);
        }
        // 解析字段名称
        else if (!name.equals(field.getName())) {
            assignment(targetObject, field, field.getName(), bundle);
        }
    }
}
 
Example 3
Source Project: cosmic   File: AccountManagerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
    accountManager = new AccountManagerImpl();
    for (final Field field : AccountManagerImpl.class.getDeclaredFields()) {
        if (field.getAnnotation(Inject.class) != null) {
            field.setAccessible(true);
            try {
                final Field mockField = this.getClass().getDeclaredField(
                        field.getName());
                field.set(accountManager, mockField.get(this));
            } catch (final Exception e) {
                // ignore missing fields
            }
        }
    }
    ReflectionTestUtils.setField(accountManager, "_userAuthenticators", Arrays.asList(userAuthenticator));
    accountManager.setSecurityCheckers(Arrays.asList(securityChecker));
    CallContext.register(callingUser, callingAccount);
}
 
Example 4
private Map<String, ColumnDefinition> getColumnDefinitionsFromFields(Object object) {
    Class<?> clazz = object.getClass();
    if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
        return Collections.emptyMap();
    }

    Map<String, ColumnDefinition> columnDefinitions = new LinkedHashMap<>();
    for (Field field : object.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(textColumnClass)) {
            TextColumn textColumn = field.getAnnotation(textColumnClass);
            String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
            columnDefinitions.put(columnKey, getColumnDefinition(textColumn, field));
        }
    }

    return columnDefinitions;
}
 
Example 5
Source Project: spring-content   File: BeanUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Field[] findFieldsWithAnnotation(Class<?> domainObjClass,
		Class<? extends Annotation> annotationClass, BeanWrapper wrapper) {
	List<Field> fields = new ArrayList<>();

	PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors();
	for (PropertyDescriptor descriptor : descriptors) {
		Field candidate = getField(domainObjClass, descriptor.getName());
		if (candidate != null) {
			if (candidate.getAnnotation(annotationClass) != null) {
				fields.add(candidate);
			}
		}
	}

	for (Field field : getAllFields(domainObjClass)) {
		if (field.getAnnotation(annotationClass) != null) {
			if (fields.contains(field) == false) {
				fields.add(field);
			}
		}
	}
	return fields.toArray(new Field[] {});
}
 
Example 6
Source Project: game-server   File: JsonUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 读取get set方法
 * 
 * @param cls
 * @param methods
 * @param fmmap
 * @param haveJSONField
 */
private static void register(Class<?> cls, Method[] methods, Map<String, FieldMethod> fmmap,
		boolean haveJSONField) {
	Field[] fields = cls.getDeclaredFields();
	for (Field field : fields) {
		try {
			if (Modifier.isStatic(field.getModifiers())) {
				continue;
			}
			JSONField fieldAnnotation = field.getAnnotation(JSONField.class);
			if (haveJSONField && fieldAnnotation == null) {
				continue;
			}
			String fieldGetName = parGetName(field);
			String fieldSetName = ReflectUtil.parSetName(field);
			Method fieldGetMet = getGetMet(methods, fieldGetName);
			Method fieldSetMet = ReflectUtil.getSetMet(methods, fieldSetName);
			if (fieldGetMet != null && fieldSetMet != null) {
				FieldMethod fgm = new FieldMethod(fieldGetMet, fieldSetMet, field);
				fmmap.put(fgm.getName(), fgm);
			} else {
				System.out.println("找不到set或get方法 " + cls.getName() + " field:" + field.getName());
			}
		} catch (Exception e) {
			System.out.println("register field:" + cls.getName() + ":" + field.getName() + " " + e);
			continue;
		}
	}
	Class<?> scls = cls.getSuperclass();
	if (scls != null) {
		register(scls, scls.getDeclaredMethods(), fmmap, haveJSONField);
	}
}
 
Example 7
Source Project: swim   File: AbstractStreamlet.java    License: Apache License 2.0 5 votes vote down vote up
private static <I, O> void recohereOutletField(int version, Streamlet<I, O> streamlet, Field field) {
  if (field.getAnnotation(Out.class) != null) {
    final Outlet<O> outlet = reflectOutletField(streamlet, field);
    outlet.recohereInput(version);
  } else if (field.getAnnotation(Inout.class) != null) {
    final Inoutlet<I, O> inoutlet = reflectInoutletField(streamlet, field);
    inoutlet.recohereInput(version);
  }
}
 
Example 8
/**
 * Test 1.
 */
@Test
public void test1(){
    Field field = FieldUtils.getDeclaredField(DangaMemCachedConfig.class, "serverList", true);
    Alias alias = field.getAnnotation(Alias.class);

    assertEquals(
                    "@com.feilong.core.bean.Alias(name=memcached.serverlist, sampleValue=172.20.31.23:11211,172.20.31.22:11211)",
                    annotationToStringBuilder.build(alias));
}
 
Example 9
Source Project: jmapper-core   File: FilesManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns tha number of annotated fields belong to the Class given in input.
 * @param aClass Class to analyze
 * @return  the number of annotated fields
 */
private static int	annotatedFieldsNumber(Class<?> aClass){
	int count = 0;
	for (Field it : aClass.getDeclaredFields()) 
		if(it.getAnnotation(JMap.class)!=null)count++;
	return count;
}
 
Example 10
public void queryEntityAfter(Object  bean) {
    if (bean == null) {
        return;
    }
    
    if(!(bean instanceof TailBean)){
    	throw new PlatformException("指定的pojo"+bean.getClass()+" 不能获取数据字典,需要继承TailBean");
    }
    
    TailBean ext  = (TailBean)bean;
    Class c = ext.getClass();
    do {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Dict.class)) {
                field.setAccessible(true);
                Dict dict = field.getAnnotation(Dict.class);
                
                try {
                    String display = "";
                    Object fieldValue = field.get(ext);
                    if (fieldValue != null) {
                        CoreDict  dbDict = dictUtil.findCoreDict(dict.type(),fieldValue.toString());
                        display = dbDict!=null?dbDict.getName():null;
                    }
                    ext.set(field.getName() + dict.suffix(), display);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
     c = c.getSuperclass();
    }while(c!=TailBean.class);
    
}
 
Example 11
Source Project: AndroidQuick   File: InjectManagerService.java    License: MIT License 5 votes vote down vote up
private static void injectStringById(ViewManager viewManager, Object object, Field field) {
    ByString stringById = field.getAnnotation(ByString.class);
    if (stringById != null) {
        int stringId = stringById.value();
        String string = viewManager.getString(stringId);
        try {
            ReflectUtils.reflect(object).field(field.getName(), string);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 12
Source Project: HtmlUnit-Android   File: BrowserVersion.java    License: Apache License 2.0 5 votes vote down vote up
private void initFeatures() {
    final SupportedBrowser expectedBrowser;
    if (isChrome()) {
        expectedBrowser = SupportedBrowser.CHROME;
    }
    else if (isFirefox52()) {
        expectedBrowser = SupportedBrowser.FF52;
    }
    else if (isFirefox()) {
        expectedBrowser = SupportedBrowser.FF45;
    }
    else if (isIE()) {
        expectedBrowser = SupportedBrowser.IE;
    }
    else {
        expectedBrowser = SupportedBrowser.EDGE;
    }

    for (final BrowserVersionFeatures features : BrowserVersionFeatures.values()) {
        try {
            final Field field = BrowserVersionFeatures.class.getField(features.name());
            final BrowserFeature browserFeature = field.getAnnotation(BrowserFeature.class);
            if (browserFeature != null) {
                for (final SupportedBrowser browser : browserFeature.value()) {
                    if (AbstractJavaScriptConfiguration.isCompatible(expectedBrowser, browser)) {
                        features_.add(features);
                    }
                }
            }
        }
        catch (final NoSuchFieldException e) {
            // should never happen
            throw new IllegalStateException(e);
        }
    }
}
 
Example 13
Source Project: SimpleFlatMapper   File: SfmAliasProvider.java    License: MIT License 5 votes vote down vote up
@Override
public String getAliasForField(Field field) {
	String alias = null;
	Column col = field.getAnnotation(Column.class);
	if (col != null) {
		alias = col.value();
	}
	return alias;
}
 
Example 14
/**
 * 参数格式化为String
 *
 * @param field
 * @param value
 * @return String
 */
public static String formatValue(Field field, Object value) {
	Class<?> fieldType = field.getType();

	ExcelField excelField = field.getAnnotation(ExcelField.class);
	if(value==null) {
		return null;
	}

	if (Boolean.class.equals(fieldType) || Boolean.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (String.class.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Short.class.equals(fieldType) || Short.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Integer.class.equals(fieldType) || Integer.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Long.class.equals(fieldType) || Long.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Float.class.equals(fieldType) || Float.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Double.class.equals(fieldType) || Double.TYPE.equals(fieldType)) {
		return String.valueOf(value);
	} else if (Date.class.equals(fieldType)) {
		String datePattern = "yyyy-MM-dd HH:mm:ss";
		if (excelField != null && excelField.dateformat()!=null) {
			datePattern = excelField.dateformat();
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
		return dateFormat.format(value);
	} else {
		throw new RuntimeException("request illeagal type, type must be Integer not int Long not long etc, type=" + fieldType);
	}
}
 
Example 15
Source Project: RuoYi-Vue   File: ExcelUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 得到所有定义字段
 */
private void createExcelField()
{
    this.fields = new ArrayList<Object[]>();
    List<Field> tempFields = new ArrayList<>();
    tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
    tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    for (Field field : tempFields)
    {
        // 单注解
        if (field.isAnnotationPresent(Excel.class))
        {
            putToField(field, field.getAnnotation(Excel.class));
        }

        // 多注解
        if (field.isAnnotationPresent(Excels.class))
        {
            Excels attrs = field.getAnnotation(Excels.class);
            Excel[] excels = attrs.value();
            for (Excel excel : excels)
            {
                putToField(field, excel);
            }
        }
    }
}
 
Example 16
private void serialize(boolean isJsonString, Object value) throws IOException {
  if (value == null) {
    return;
  }
  Class<?> valueClass = value.getClass();
  if (Data.isNull(value)) {
    writeNull();
  } else if (value instanceof String) {
    writeString((String) value);
  } else if (value instanceof Number) {
    if (isJsonString) {
      writeString(value.toString());
    } else if (value instanceof BigDecimal) {
      writeNumber((BigDecimal) value);
    } else if (value instanceof BigInteger) {
      writeNumber((BigInteger) value);
    } else if (value instanceof Long) {
      writeNumber((Long) value);
    } else if (value instanceof Float) {
      float floatValue = ((Number) value).floatValue();
      Preconditions.checkArgument(!Float.isInfinite(floatValue) && !Float.isNaN(floatValue));
      writeNumber(floatValue);
    } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
      writeNumber(((Number) value).intValue());
    } else {
      double doubleValue = ((Number) value).doubleValue();
      Preconditions.checkArgument(!Double.isInfinite(doubleValue) && !Double.isNaN(doubleValue));
      writeNumber(doubleValue);
    }
  } else if (value instanceof Boolean) {
    writeBoolean((Boolean) value);
  } else if (value instanceof DateTime) {
    writeString(((DateTime) value).toStringRfc3339());
  } else if ((value instanceof Iterable<?> || valueClass.isArray())
      && !(value instanceof Map<?, ?>)
      && !(value instanceof GenericData)) {
    writeStartArray();
    for (Object o : Types.iterableOf(value)) {
      serialize(isJsonString, o);
    }
    writeEndArray();
  } else if (valueClass.isEnum()) {
    String name = FieldInfo.of((Enum<?>) value).getName();
    if (name == null) {
      writeNull();
    } else {
      writeString(name);
    }
  } else {
    writeStartObject();
    // only inspect fields of POJO (possibly extends GenericData) but not generic Map
    boolean isMapNotGenericData = value instanceof Map<?, ?> && !(value instanceof GenericData);
    ClassInfo classInfo = isMapNotGenericData ? null : ClassInfo.of(valueClass);
    for (Map.Entry<String, Object> entry : Data.mapOf(value).entrySet()) {
      Object fieldValue = entry.getValue();
      if (fieldValue != null) {
        String fieldName = entry.getKey();
        boolean isJsonStringForField;
        if (isMapNotGenericData) {
          isJsonStringForField = isJsonString;
        } else {
          Field field = classInfo.getField(fieldName);
          isJsonStringForField = field != null && field.getAnnotation(JsonString.class) != null;
        }
        writeFieldName(fieldName);
        serialize(isJsonStringForField, fieldValue);
      }
    }
    writeEndObject();
  }
}
 
Example 17
Source Project: spring-data-simpledb   File: MetadataParser.java    License: MIT License 4 votes vote down vote up
private static boolean hasUnsupportedAnnotations(Field field) {
	return (field.getAnnotation(Attributes.class) != null);
}
 
Example 18
public static boolean asArray(Field f) {
    return (f.getAnnotation(AsArray.class) != null);
}
 
Example 19
Source Project: jeecg-boot   File: DictAspect.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
 * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
 * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
 * 例输入当前返回值的就会多出一个sex_dictText字段
 * {
 *      sex:1,
 *      sex_dictText:"男"
 * }
 * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
 *  customRender:function (text) {
 *               if(text==1){
 *                 return "男";
 *               }else if(text==2){
 *                 return "女";
 *               }else{
 *                 return text;
 *               }
 *             }
 *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
 * @param result
 */
private void parseDictText(Object result) {
    if (result instanceof Result) {
        if (((Result) result).getResult() instanceof IPage) {
            List<JSONObject> items = new ArrayList<>();
            for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
                ObjectMapper mapper = new ObjectMapper();
                String json="{}";
                try {
                    //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                     json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败"+e.getMessage(),e);
                }
                JSONObject item = JSONObject.parseObject(json);
                //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                //for (Field field : record.getClass().getDeclaredFields()) {
                for (Field field : oConvertUtils.getAllFields(record)) {
                //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = field.getAnnotation(Dict.class).dicCode();
                        String text = field.getAnnotation(Dict.class).dicText();
                        String table = field.getAnnotation(Dict.class).dictTable();
                        String key = String.valueOf(item.get(field.getName()));

                        //翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);

                        log.debug(" 字典Val : "+ textValue);
                        log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+": "+ textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                    //date类型默认转换string格式化日期
                    if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
                        SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                    }
                }
                items.add(item);
            }
            ((IPage) ((Result) result).getResult()).setRecords(items);
        }

    }
}
 
Example 20
/**
 * Returns a field annotation based on an annotation type
 * 
 * @param field the annotation Field
 * @param annotationClass the annotation Class
 * @return The Annotation type
 * @deprecated As of 1.3
 */
@Deprecated
public <T extends Annotation> T getAnnotation(Field field, Class<T> annotationClass) {
    return field.getAnnotation(annotationClass);
}