Java注解

什么是注解

注解對(duì)于開(kāi)發(fā)人員來(lái)講既熟悉又陌生,熟悉是因?yàn)橹灰闶亲鲩_(kāi)發(fā),都會(huì)用到注解(常見(jiàn)的@Override);陌生是因?yàn)榧词共皇褂米⒔庖舱粘D軌蜻M(jìn)行開(kāi)發(fā);注解不是必須的,但了解注解有助于我們深入理解某些第三方框架(比如Android Support Annotations、JUnit、xUtils、ActiveAndroid等),提高工作效率。

常見(jiàn)注解

API
Android開(kāi)發(fā)過(guò)程中使用到的注解主要來(lái)自如下幾個(gè)地方:

  • Android SDK:在包android.annotation下;
  • Android Annotation Support包:在包android.support.annotation下;
  • JDK:在包java.lang下;

第三方框架中的自定義注解;

最常見(jiàn)注解

  • @Override
    屬于標(biāo)記注解,不需要設(shè)置屬性值;只能添加在方法的前面,用于標(biāo)記該方法是復(fù)寫(xiě)的父類中的某個(gè)方法,如果在父類沒(méi)有的方法前面加上@Override注解,編譯器會(huì)報(bào)錯(cuò):
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
  • @Deprecated
    屬于標(biāo)記注解,不需要設(shè)置屬性值;可以對(duì)構(gòu)造方法、變量、方法、包、參數(shù)標(biāo)記,告知用戶和編譯器被標(biāo)記的內(nèi)容已不建議被使用,如果被使用,編譯器會(huì)報(bào)警告,但不會(huì)報(bào)錯(cuò),程序也能正常運(yùn)行:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE})
public @interface Deprecated {
}
  • @SuppressWarnings
    可以對(duì)構(gòu)造方法、變量、方法、包、參數(shù)標(biāo)記,用于告知編譯器忽略指定的警告,不用再編譯完成后出現(xiàn)警告信息:
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}
  • @TargetApi
    可以對(duì)接口、方法、構(gòu)造方法標(biāo)記,如果在應(yīng)用中指定minSdkVersion為8,但有地方需要使用API 11中的方法,為了避免編譯器報(bào)錯(cuò),在調(diào)用API11中方法的接口、方法或者構(gòu)造方法前面加上@Target(11),這樣該方法就可以使用<=11的API接口了。雖然這樣能夠避免編譯器報(bào)錯(cuò),但在運(yùn)行時(shí)需要注意,不能在API低于11的設(shè)備中使用該方法,否則會(huì)crash(可以獲取程序運(yùn)行設(shè)備的API版本來(lái)判斷是否調(diào)用該方法):
@Target({TYPE, METHOD, CONSTRUCTOR})
@Retention(RetentionPolicy.CLASS)
public @interface TargetApi {
    /**
     * This sets the target api level for the type..
     */
    int value();
}
  • @SuppressLint
    和@Target的功能差不多,但使用范圍更廣,主要用于避免在lint檢查時(shí)報(bào)錯(cuò):
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.CLASS)
public @interface SuppressLint {
    /**
     * The set of warnings (identified by the lint issue id) that should be
     * ignored by lint. It is not an error to specify an unrecognized name.
     */
    String[] value();
}

自定義注解

通過(guò)閱讀注解類的源碼可以發(fā)現(xiàn),任何一個(gè)注解類都有如下特征:

注解類會(huì)被@interface標(biāo)記;

注解類的頂部會(huì)被@Documented、@Retention、@Target、@Inherited這四個(gè)注解標(biāo)記(@Documented、@Inherited可選,@Retention、@Target必須要有);

@UiThread源碼:

@Documented
@Retention(CLASS)
@Target({METHOD,CONSTRUCTOR,TYPE})
public @interface UiThread {
}

元注解

上文提到的四個(gè)注解:@Documented、@Retention、@Target、@Inherited就是元注解,它們的作用是負(fù)責(zé)注解其它注解,主要是描述注解的一些屬性,任何注解都離不開(kāi)元注解(包括元注解自身,通過(guò)元注解可以自定義注解),元注解的用戶是JDK,JDK已經(jīng)幫助我們實(shí)現(xiàn)了這四個(gè)注解的邏輯。這四個(gè)注解在JDK的java.lang.annotation包中。對(duì)每個(gè)元注解的詳細(xì)說(shuō)明如下:

@Target:

作用:用于描述注解的使用范圍,即被描述的注解可以用在什么地方;

取值:

  • CONSTRUCTOR:構(gòu)造器;
  • FIELD:實(shí)例;
  • LOCAL_VARIABLE:局部變量;
  • METHOD:方法;
  • PACKAGE:包;
  • PARAMETER:參數(shù);
  • TYPE:類、接口(包括注解類型) 或enum聲明。

示例:

/***
 *
 * 實(shí)體注解接口
 */
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Entity {
    /***
     * 實(shí)體默認(rèn)firstLevelCache屬性為false
     * @return boolean
     */
    boolean firstLevelCache() default false;
    /***
     * 實(shí)體默認(rèn)secondLevelCache屬性為false
     * @return boolean
     */
    boolean secondLevelCache() default true;
    /***
     * 表名默認(rèn)為空
     * @return String
     */
    String tableName() default "";
    /***
     * 默認(rèn)以""分割注解
     */
    String split() default "";
}

@Retention:

作用:表示需要在什么級(jí)別保存該注解信息,用于描述注解的生命周期,即被描述的注解在什么范圍內(nèi)有效;

取值:

  • SOURCE:在源文件中有效,即源文件保留;
  • CLASS:在class文件中有效,即class保留;
  • RUNTIME:在運(yùn)行時(shí)有效,即運(yùn)行時(shí)保留;

示例:

/***
 * 字段注解接口
 */
@Target(value = {ElementType.FIELD})//注解可以被添加在實(shí)例上
@Retention(value = RetentionPolicy.RUNTIME)//注解保存在JVM運(yùn)行時(shí)刻,能夠在運(yùn)行時(shí)刻通過(guò)反射API來(lái)獲取到注解的信息
public @interface Column {
    String name();//注解的name屬性
}

@Documented:

作用:用于描述其它類型的annotation應(yīng)該被作為被標(biāo)注的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化。

取值:它屬于標(biāo)記注解,沒(méi)有成員;

示例:

@Documented
@Retention(CLASS)
@Target({METHOD,CONSTRUCTOR,TYPE})
public @interface UiThread {
}

@Inherited:

作用:用于描述某個(gè)被標(biāo)注的類型是可被繼承的。如果一個(gè)使用了@Inherited修飾的annotation類型被用于一個(gè)class,則這個(gè)annotation將被用于該class的子類。

取值:它屬于標(biāo)記注解,沒(méi)有成員;

示例:

/**  
 * @author wangsheng 
 **/  
@Inherited  
public @interface Greeting {  
    public enum FontColor{ BULE,RED,GREEN};  
    String name();  
    FontColor fontColor() default FontColor.GREEN;  
} 

如何自定義注解

使用@interface自定義注解時(shí),自動(dòng)繼承了java.lang.annotation.Annotation接口,由編譯程序自動(dòng)完成其他細(xì)節(jié)。在定義注解時(shí),不能繼承其他的注解或接口。@interface用來(lái)聲明一個(gè)注解,其中的每一個(gè)方法實(shí)際上是聲明了一個(gè)配置參數(shù)。方法的名稱就是參數(shù)的名稱,返回值類型就是參數(shù)的類型(返回值類型只能是基本類型、Class、String、enum)??梢酝ㄟ^(guò)default來(lái)聲明參數(shù)的默認(rèn)值。

自定義注解格式:

元注解
public @interface 注解名{
    定義體;
}

注解參數(shù)可支持的數(shù)據(jù)類型:
1、所有基本數(shù)據(jù)類型(int,float,boolean,byte,double,char,long,short);
2、String類型;
3、Class類型;
4、enum類型;
5、Annotation類型;
6、以上所有類型的數(shù)組。

特別說(shuō)明:

1、注解類中的方法只能用public或者默認(rèn)這兩個(gè)訪問(wèn)權(quán)修飾,不寫(xiě)public就是默認(rèn),eg:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    public enum Color{ BULE,RED,GREEN};
    Color fruitColor() default Color.GREEN;
}

2、如果注解類中只有一個(gè)成員,最好把方法名設(shè)置為"value",比如:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}

3、注解元素必須有確定的值,要么在定義注解的默認(rèn)值中指定,要么在使用注解時(shí)指定,非基本類型的注解元素的值不可為null。因此, 使用空字符串或0作為默認(rèn)值是一種常用的做法。

實(shí)例演示:
ToDo.java:注解類

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
    public enum Priority {LOW, MEDIUM, HIGH}
    public enum Status {STARTED, NOT_STARTED}    
    String author() default "Yash";
    Priority priority() default Priority.LOW;
    Status status() default Status.NOT_STARTED;
}

BusinessLogic:使用注解的類

public class BusinessLogic {
    public BusinessLogic() {
        super();
    }

    public void compltedMethod() {
        System.out.println("This method is complete");
    }    

    @Todo(priority = Todo.Priority.HIGH)
    public void notYetStartedMethod() {
        // No Code Written yet
    }

    @Todo(priority = Todo.Priority.MEDIUM, author = "Uday", status = Todo.Status.STARTED)
    public void incompleteMethod1() {
        //Some business logic is written
        //But its not complete yet
    }

    @Todo(priority = Todo.Priority.LOW, status = Todo.Status.STARTED )
    public void incompleteMethod2() {
        //Some business logic is written
        //But its not complete yet
    }
}

TodoReport.java:解析注解信息

public class TodoReport {
    public TodoReport() {
        super();
    }

    public static void main(String[] args) {
        getTodoReportForBusinessLogic();
    }

    /**
     * 解析使用注解的類,獲取通過(guò)注解設(shè)置的屬性
     */
    private static void getTodoReportForBusinessLogic() {
        Class businessLogicClass = BusinessLogic.class;
        for(Method method : businessLogicClass.getMethods()) {
            Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
            if(todoAnnotation != null) {
                System.out.println(" Method Name : " + method.getName());
                System.out.println(" Author : " + todoAnnotation.author());
                System.out.println(" Priority : " + todoAnnotation.priority());
                System.out.println(" Status : " + todoAnnotation.status());
                System.out.println(" --------------------------- ");
            }
        }
    }
}

參考

【1】深入淺出Java注解

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容