简体   繁体   English

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

[英]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) . 所以我需要Field[] getAllAnnotatedFields(MyClass.class, MyAnnotation.class)

I could write that method on my own, but I wonder, if there exists some util method. 我可以自己编写该方法,但我想知道是否存在某些util方法。 (I cannot found one in Apache commons, Guava or Google reflections). (我在Apache Commons,Guava或Google反映中找不到一个)。

This is my solution using Apache commons: 这是我使用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.

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