import java.lang.annotation.*; import java.lang.reflect.Method; @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MethodInfo { String author() default "hupeng"; String version() default "1.0"; String date(); String comment(); }
@Target說明了Annotation所修飾的對象範圍:Annotation可被用於 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。java
做用:用於描述註解的使用範圍(即:被描述的註解能夠用在什麼地方)ide
取值(ElementType)有:工具
1.CONSTRUCTOR:用於描述構造器
2.FIELD:用於描述域
3.LOCAL_VARIABLE:用於描述局部變量
4.METHOD:用於描述方法
5.PACKAGE:用於描述包
6.PARAMETER:用於描述參數
7.TYPE:用於描述類、接口(包括註解類型) 或enum聲明code
@Retention定義了該Annotation被保留的時間長短:某些Annotation僅出如今源代碼中,而被編譯器丟棄;而另外一些卻被編譯在class文件中;編譯在class文件中的Annotation可能會被虛擬機忽略,而另外一些在class被裝載時將被讀取(請注意並不影響class的執行,由於Annotation與class在使用上是被分離的)。使用這個meta-Annotation能夠對 Annotation的「生命週期」限制。對象
做用:表示須要在什麼級別保存該註釋信息,用於描述註解的生命週期(即:被描述的註解在什麼範圍內有效)繼承
取值(RetentionPoicy)有:接口
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在運行時有效(即運行時保留)生命週期
@Documented用於描述其它類型的annotation應該被做爲被標註的程序成員的公共API,所以能夠被例如javadoc此類的工具文檔化。Documented是一個標記註解,沒有成員。文檔
@Inherited 元註解是一個標記註解,@Inherited闡述了某個被標註的類型是被繼承的。若是一個使用了@Inherited修飾的annotation類型被用於一個class,則這個annotation將被用於該class的子類。get
注意:@Inherited annotation類型是被標註過的class的子類所繼承。類並不從它所實現的接口繼承annotation,方法並不從它所重載的方法繼承annotation。
從java5版本開始,自帶了三種標準annontation類型,
下面咱們來使用Java內置的Annotation 和 自定義的Annotation
public class AnnotationExample { @Override @MethodInfo(author = "xxx",version = "1.0",date = "2015/03/26",comment = "override toString()") public String toString() { return "AnnotationExample{}"; } @Deprecated @MethodInfo(comment = "deprecated method", date = "2015/03/26") public static void oldMethod() { System.out.println("old method, don't use it."); } @SuppressWarnings({ "unchecked", "deprecation" }) @MethodInfo(author = "Pankaj", comment = "Main method", date = "Nov 17 2012", version = "1.0") public static void genericsTest() { oldMethod(); } }
注意咱們的Annotation的Retention Policy 必須是RUNTIME,不然咱們沒法在運行時從他裏面得到任何數據。
import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * Created by Administrator on 2015/3/26. */ public class AnnotationParsing { public static void main(String[] args) { for (Method method: AnnotationExample.class.getMethods()) { if (method.isAnnotationPresent(MethodInfo.class)) { for (Annotation annotation:method.getAnnotations()) { System.out.println(annotation + " in method:"+ method); } MethodInfo methodInfo = method.getAnnotation(MethodInfo.class); if ("1.0".equals(methodInfo.version())) { System.out.println("Method with revision no 1.0 = " + method); } } } } }