自定義註解的學習 一

2021-06-27 00:57:33 字數 1377 閱讀 3941

註解(annotation),也叫元資料。一種**級別的說明。它是jdk5.0及以後版本引入的乙個特性,與類、介面、列舉是在同乙個層次。它可以宣告在包、類、字段、方法、區域性變數、方法引數等的前面,用來對這些元素進行說明,注釋。

自定義註解類似於介面,為了區分與介面的區別,們需要將它宣告為@inte***ce

自定義註解分為以下幾個方面:

@documented:指定其是否在文件中生成

publice enum elementtype
@retention(retentionpolicy.runtime)  用來指定該註解的生成方式,同樣是列舉型別,有一下幾個值:

public enum retentionpolicy

@inherited  讓它允許繼承,可作用到子類

接下來看幾個具體的demo:

demo1:

定義註解如下:

@documented

@target(elementtype.type)

@retention(retentionpolicy.runtime)

public @inte***ce helloworld1

其中classname,author,description等既是屬性也是方法。

引用註解

@helloworld1 (classname="liuhang",author="helloworld",description="2014-11-14",date="it's a test anotation")

public class helloworldtest1

}

demo2:

定義註解如下:

@documented

@retention(retentionpolicy.runtime)

@target(elementtype.field)

@inherited

public @inte***ce myanotation

在該註解中elementtype.field表示該註解只能用於屬性上,在屬性後邊的default代表預設值

註解的處理類:

public class myanotationparse 

if (fields[i].getname().equals("age"))

} }

}

引用註解:

public class testmyanotation 

}

自定義註解

target elementtype.field retention retentionpolicy.runtime public inte ce setvalue以上就是乙個自定義的註解,下面來進行說明。target elementtype.field 表示支援該註解的程式元素,field就是屬性...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...