java自訂註解以及註解的簡單介紹

來源:互聯網
上載者:User

標籤:

jdk內建註解
@Override 覆蓋父類的方法
@Deprecated  註解一個方法 表示該方法過時了
@Suppvisewarnings     @SupressWarnings("deprecation")//忽略警告

常見第三方註解
Spring:
@Autowired   自動產生一個類的執行個體
@Service
@Repository



Mybatis:
@InsertProvider
@UpdateProvider
@Options

註解的分類
運行機制化分
源碼註解 註解只在源碼中出現 class檔案就沒有了
編譯註解  在源碼和.class 檔案中都存在
運行註解  運行階段起作用 影響程式的運行邏輯


來源來分
jdk註解
第三方的註解
自訂的註解

元註解 註解的註解


自訂註解
文法要求
元註解
@Target(ElementType.METHOD,ElementType.TYPE) //註解的範圍 可以用在 CONSTRUCTOR構造方法聲明 FIELD欄位聲明 LOCAL_VARIABLE局部變數 METHOD方法聲明 PACKAGE包聲明 PARAMETER參數聲明 TYPE類介面
@Retention(RetentionPolicy.RUNTIME) 生命週期SOURCE 在源碼時顯示 編譯被丟棄  CLASS 編譯時間記錄到class中,運行時忽略 RUNTIME 運行時存在,可以通過反射擷取
@Inherited   允許子類繼承  繼承只會繼承類上面的註解 不會繼承方法上的註解
@Documented  產生javadoc包含註解資訊
public @interface Description{
    String desc();
    String author();
    int age() default 18;
}

使用@interface關鍵字定義註解
成員以無參無異常方式聲明
可以用defalut成員指定預設值
成員類型包括原始類型 以及String class Annotation Enumeration
如果註解只有一個成員,則成員名必須取名為value() ,在使用時可以忽略成員名和賦值號=
註解類可以沒有成員 成為標識註解


使用註解
@Description(desc="gac",autor="gac1",age=18)
public String eyeColor(){
    return "red";
}


解析註解
通過反射擷取類,函數或成員上的運行時註解資訊,從而實現動態控製程序啟動並執行邏輯

public class ParseAnn{
    //使用類載入器載入類 獲得類上的註解
    try{
        Class c = Class.forName("com.ann.test.Child");//這個類使用了定義的註解  
        //2.找到類上面的註解
        boolean isExists = c.isAnnotationPresent(Description.class);
        if(isExits){
            //拿到註解執行個體
            Description d = (Description)c.getAnnotation(Description.class);
            System.out.println(d.value());
        }






                //找到方法上的註解
        Method[] ms = c.getMethods();
        for(Method m:ms){
            boolean isMExits = m.isAnnotationPresent(Description.class);
            if(isMExits){
                Description d = (Description)m.getAnnotation(Description.class);
                System.out.println(d.value());
            }
        }




        //另外一種解析方法
        for(Method m : ms){
            Annotation[] as = m.getAnnotations();
            for(Annotation a:as){
                if(a instanceof Description){
                    Description d = (Description)a;
                    System.out.println(d.value());
                }
            }
        }
    }catch(ClassNotFoundException e){

        e.printStackTrace();
    }

    
}
































著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

java自訂註解以及註解的簡單介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.