为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MMTTMM 2022-01-12 14:15:49
我需要使用某种方式来获取所有带有特定注释的字段。注释可能位于字段或(超类的)getter,例如public MyClass {    @MyAnnotation    String myName;    int myAge;    @MyAnnotation    int getMyAge() { return myAge; }}所以我需要Field[] getAllAnnotatedFields(MyClass.class, MyAnnotation.class).我可以自己编写该方法,但我想知道是否存在一些 util 方法。(我在 Apache commons、Guava 或 Google 反射中找不到一个)。
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

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

}


查看完整回答
反对 回复 2022-01-12
  • 1 回答
  • 0 关注
  • 294 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号