亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

我可以獲得任何注釋值,而不使用注釋的名稱嗎?

我可以獲得任何注釋值,而不使用注釋的名稱嗎?

藍山帝景 2022-09-28 10:09:19
我想編寫一個返回注釋方法值的方法。我試圖使用這個變體,沒有任何成功參數:clazz - 具有注釋的 Сlass注釋克拉茲 - 我的注釋.class參數名稱 - 方法的名稱這是我的代碼:public static Object getAnnotationValue(Class clazz, Class annotationClazz, String parametersName) {    Annotation an = clazz.getAnnotation(annotationClazz);    if (an.equals(null)) {        throw new CoreError("Класс " + clazz + " не содержит аннотацию " + annotationClazz);    }    PageName pn = (PageName) an;    try {        //its working!        System.out.println(pn.value());        //not working :(        System.out.println(an.getClass().getMethod(parametersName).getDefaultValue()); //not working :(        System.out.println(an.annotationType().getDeclaredMethod(parametersName, annotationClazz).getDefaultValue());        System.out.println(pn.getClass().getMethod(parametersName).getDefaultValue());        System.out.println(pn.annotationType().getDeclaredMethod(parametersName, annotationClazz).getDefaultValue());    } catch (NoSuchMethodException e) {        e.printStackTrace();    }}這有可能嗎?
查看完整描述

1 回答

?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

您的代碼一直在尋找默認值,但您的問題從未提及默認值是否存在。若要獲取提供的值,必須在實例上使用該方法。invoke

此外,在大多數情況下,您正在使用和錯誤。getMethodgetDeclaredMethod

下面是一個工作示例:

public static Object getAnnotationValue(Class clazz, Class annotationClazz, String parameterName) {  
  Annotation an = clazz.getAnnotation(annotationClazz);
    System.out.println(an.annotationType().getMethod(parameterName).invoke(an));
}

因此,對于這樣的類:

@PageName("testPage") //Same as @PageName(value = "testPage")public class Example {}

getAnnotationValue(Example.class, PageName.class, "value")

將打印

測試頁


查看完整回答
反對 回復 2022-09-28
  • 1 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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