Java 注解Annotation研究

目前主流框架都支持注解。比如Android平臺上的 Retrofit,EventBus,Butterknife等
Java Web: Spring MVC ,MyBatis等.注解是從Java SDK 1.5 開始啟動使用的,使用注解到底有什么好處呢?

對于配置文件需要添加較多邏輯代碼來處理,而注解只需要注解元 數據就可以區分,代碼整潔,閱讀性好,減少配置文件等。

annotation.png

如上圖所示:
Java的注解分為元注解和標準注解。

  • 標準注解:系統提供的注解

@Deprecated :表示已經過期,不推薦使用.比如你有一個方法現在不想用了,但是其他人調用了,刪掉會影響其他代碼。這樣用這個標記來說明.

@Documented
@Retention(RetentionPolicy.RUNTIME)//運行期runtime
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})//范圍
public @interface Deprecated {
}
@Deprecated
public void test(){
}

@Override 主要作用是覆蓋父類方法

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)//在源文件中出現,在編譯后會被編譯器丟棄
public @interface Override {
}

比如android onCreate方法,覆蓋父類方法

 @Override
 protected void onCreate(Bundle savedInstanceState) {
}

比如java toString()方法,覆蓋java lang toString方法

 @Override
  public String toString() {
        return super.toString();
   }

@SupressWarning 關閉不當的編譯器警告信息
比如

  • 元注解:可以自己定義注解

@Retention 表示需要在什么級別保存該注解信息,標記有下面3個參數可選

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,//注解將被編譯器丟棄

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,//注解在class文件可用,但是會VM丟棄

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME//VM運行期也會保留注解,可用用反射機制可用讀取對應的數據
}

@Target 表示被描述的注解用于什么地方,可用運用到地方如下

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();//這邊是一個ElementType數組
}

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,//用于描述類,接口 或枚舉聲明

    /** Field declaration (includes enum constants) */
    FIELD,//用于描述域

    /** Method declaration */
    METHOD,//用于描述方法

    /** Formal parameter declaration */
    PARAMETER,//用于描述參數

    /** Constructor declaration */
    CONSTRUCTOR,//用于描述構造器

    /** Local variable declaration */
    LOCAL_VARIABLE,//用于描述局部變量

    /** Annotation type declaration */
    ANNOTATION_TYPE,//用于描述Annotation type

    /** Package declaration */
    PACKAGE,//描述包

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

@Documented用于描述其它類型的annotation應該被作為被標注的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化。Documented是一個標記注解,沒有成員.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

@Inherited 元注解是一個標記注解,@Inherited闡述了某個被標注的類型是被繼承的,則這個annotation將被用于該class的子類。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

自定義自己的Annotation 格式如下
public @interface 注解名 {定義體}

定義體里面一般如下圖所示:

anntion2.png

舉個栗子寫個Demo吧:
定義一個Person Annotation 里面定義了2個方法 say 和move 方法.

@Target({ElementType.METHOD,ElementType.TYPE,ElementType.LOCAL_VARIABLE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonAnnotation {
   public String say() default "hello";
   public String move() default "walk";
  Sex  sex() default Sex.MAN;//枚舉類型
}

定義一個UserAnnotation 定義name, age 和 PersonAnnotation annotation

@Target({ElementType.METHOD , ElementType.TYPE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})//可以修飾方法,實例變量,local 變量
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAnnotation {
    String name() default "";
    String age() default "";
    PersonAnnotation person();//使用了Annotation類型
}

定義性別enum.

public enum Sex {
    MAN,WOMEN,OTHER
}

上面的代碼定義的不錯,那怎么使用呢?答案是反射,直接上代碼吧??
定義User類

@UserAnnotation//因為在Target定義了ElementType.TYPE可以修飾類
public class User {
    @UserAnnotation(name = "Star")//因為在Target中定義了ElementType.FIELD就可以定義在實例變量中拉
    protected String name;
    @UserAnnotation(age = 100)
    int age;
    @UserAnnotation(name = "wong" , age = 1000)
    protected String value;
    @UserAnnotation(name = "GEAK",age = 90)//因為在Target中定義了ElementType.METHOD
    public void getUserInfo(String name,int age){
        System.out.println("the name is:"+name+"\tthe age is:"+age);
    }
    public void getInfo(){
        System.out.println("=======getInfo start=====");
        System.out.println("the name is:"+this.name+"\tthe age is:"+this.age);
        System.out.println("=======getInfo end=====");
    }


}

定義了自己的元數據,下面是測試怎么使用

    @Test
    public void test() {
        //User user = new User();
        System.out.println("startTest");
        Class<User> u = User.class;
        try {
            Method method = u.getMethod("getUserInfo", new Class[]{String.class, int.class});
            UserAnnotation userAnnotation = method.getAnnotation(UserAnnotation.class);
            System.out.println("the name is:" + userAnnotation.name() + "the age is:" + userAnnotation.age());
            if (method != null) {
                method.invoke(u.newInstance(), userAnnotation.name(), userAnnotation.age());
            }
            Field fields[] = u.getDeclaredFields();
            Field f = u.getDeclaredField("value");
            UserAnnotation userAnnotation1 = f.getAnnotation(UserAnnotation.class);
            System.out.println("the f name is:" + userAnnotation1.name() + "the f age is:" + userAnnotation1.age());
            for (Field field : fields) {
                if (field.isAnnotationPresent(UserAnnotation.class)) {
                    System.out.println("the name is:" + field.getName());
                    UserAnnotation annotation = field.getAnnotation(UserAnnotation.class);
                    if (annotation != null) {
                        System.out.println("the name is:" + annotation.name() + "the age is:" + annotation.age());
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

獲取對應的User Class ,有下面兩種方式

  • 獲取Class相關
    1.Class<User> u = User.class; //通過Class直接獲取
    2.Class<User> u = Class.forName("User");//通過name獲取

  • Class中主要用到的方法
    Method[] getMethods() //獲取所有的方法包括父類的方法
    Field[] getFields() //獲取所有實例變量包括父類的實例
    Field[] getDeclaredFields()//獲取所有的方法不包括父類的方法
    Method[] getDeclaredMethods()//獲取所有實例變量不包括父類的實例

  • 獲取Annotation
    Method.getAnnotation(Annatation.class)//獲取方法上面的Annotation
    Field.getAnnotation(Annatation.class)//獲取filed上的Annotation

獲取結果:

the name is:GEAKthe age is:90 //獲取到方法上的Annotation
the name is:GEAK    the age is:90//獲取到方法上的Annotation
the f name is:wongthe f age is:1000//利用反射的機制來調用方法
the name is:name
the name is:Starthe age is:10//獲取對應實例的name上的Annotation
the name is:age
the name is:the age is:100
the name is:value
the name is:wongthe age is:1000

總結:
通過Annotation和反射機制來進行合理的配置你的源代碼.這樣就可以省去大部分的if else或者初始化等工作.

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372

推薦閱讀更多精彩內容