[英]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.