简体   繁体   中英

Gets all fields with a specific annotation on the field or the getter

I need to use some way to get all fields that are annotated with a specific annotation. The annotation may be at the field or the getter (of a super class), like

public MyClass {

    @MyAnnotation
    String myName;

    int myAge;

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

So I need Field[] getAllAnnotatedFields(MyClass.class, MyAnnotation.class) .

I could write that method on my own, but I wonder, if there exists some util method. (I cannot found one in Apache commons, Guava or Google reflections).

This is my solution using 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM