java註解(一)

雖然平時有使用註解,不過沒有深入瞭解,今天無聊,重新從基礎深入瞭解整理下;

java註解是附加在代碼中的一些元信息,用於一些工具在編譯、運行時進行解析和使用,起到說明、配置的功能。
    註解不會也不能影響代碼的實際邏輯,僅僅起到輔助性的作用。包含在 java.lang.annotation 包中。

1、元註解
    元註解是指註解的註解。包括  @Retention @Target @Document @Inherited四種。
    1.1、@Retention: 定義註解的保留策略
    @Retention(RetentionPolicy.SOURCE) //註解僅存在於源碼中,在class字節碼文件中不包含
    @Retention(RetentionPolicy.CLASS)  //默認的保留策略,註解會在class字節碼文件中存在,但運行時無法獲得,
    @Retention(RetentionPolicy.RUNTIME)//註解會在class字節碼文件中存在,在運行時可以通過反射獲取到

    1.2、@Target:定義註解的作用目標
    @Target(ElementType.TYPE)   //接口、類、枚舉、註解
    @Target(ElementType.FIELD) //字段、枚舉的常量
    @Target(ElementType.METHOD) //方法
    @Target(ElementType.PARAMETER) //方法參數
    @Target(ElementType.CONSTRUCTOR)  //構造函數
    @Target(ElementType.LOCAL_VARIABLE)//局部變量
    @Target(ElementType.ANNOTATION_TYPE)//註解
    @Target(ElementType.PACKAGE) ///包

    elementType 可以有多個,一個註解可以爲類的,方法的,字段的等等
    1.3、@Document:說明該註解將被包含在javadoc中
    1.4、@Inherited:說明子類可以繼承父類中的該註解

下面是自定義註解的一個例子
    2、註解的自定義

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface HelloWorld {
    	public String name() default "";
    }
    3、註解的使用,測試
    public class SayHello {
      @HelloWorld(name = "Intl")
      public void sayHello(String name) {
    	System.out.println(name + "say hello world!");
      }
    }
    4、解析註解
    java的反射機制可以幫助,得到註解,代碼如下:
public class AnnTest {
    public void parseMethod(Class<?> clazz) {
    Object obj;
    try {
    	// 通過默認構造方法創建一個新的對象
    	obj = clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
    	for (Method method : clazz.getDeclaredMethods()) {
    		HelloWorld say = method.getAnnotation(HelloWorld.class);
    		String name = "";
    		if (say != null){
    			name = say.name();
    			System.out.println(name);
    			method.invoke(obj, name);
    		}
   	 }
   	 } catch(Exception e) {
    		e.printStackTrace();
    	 }
    }
    public static void main(String[] args) {
    	AnnTest t = new AnnTest();
    	t.parseMethod(SayHello.class);
    }
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章