[英]Gets all fields with a specific annotation on the field or the getter
我需要使用某種方式來獲取所有帶有特定注釋的字段。 注釋可以在現場或(超類的)吸氣劑處,例如
public MyClass {
@MyAnnotation
String myName;
int myAge;
@MyAnnotation
int getMyAge() { return myAge; }
}
所以我需要Field[] getAllAnnotatedFields(MyClass.class, MyAnnotation.class)
。
我可以自己編寫該方法,但我想知道是否存在某些util方法。 (我在Apache Commons,Guava或Google反映中找不到一個)。
這是我使用Apache Commons的解決方案:
public static Collection<String> getPropertyNamesListWithAnnotation(Class<?> targetClass, Class<? extends Annotation> annotationClass) {
Set<String> fieldNamesWithAnnotation = FieldUtils.getFieldsListWithAnnotation(targetClass, annotationClass).stream().map(Field::getName).collect(Collectors.toSet());
fieldNamesWithAnnotation.addAll(MethodUtils.getMethodsListWithAnnotation(targetClass, annotationClass, true, false).stream()
.map(Method::getName)
.filter(LangHelper::isValidGetterOrSetter)
.map(name -> StringUtils.uncapitalize(RegExUtils.replaceFirst(name, "^(get|set|is)", "")))
.collect(Collectors.toSet()));
return fieldNamesWithAnnotation;
}
private static boolean isValidGetterOrSetter(String methodName) {
if (!StringUtils.startsWithAny(methodName, "get", "set", "is")) {
LOG.warn("Annotated method is no valid getter or setter: '{}' -> Ignoring", methodName);
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.