第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取在字段或 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 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號