获取所有在字段或getter上具有特定注释的字段

时间:2018-11-10 20:45:59

标签: java reflection annotations

我需要使用某种方式来获取所有带有特定注释的字段。注释可以在字段或(超类的)获取器上,例如

public MyClass {

    @MyAnnotation
    String myName;

    int myAge;

    @MyAnnotation
    int getMyAge() { return myAge; }
}

所以我需要Field[] getAllAnnotatedFields(MyClass.class, MyAnnotation.class)

我可以自己编写该方法,但是我想知道是否存在某些util方法。 (我在Apache Commons,Guava或Google反映中找不到一个。)

1 个答案:

答案 0 :(得分:0)

这是我使用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;
}