Java 注解使用

本文摘自 https://my.oschina.net/itgaowei/blog/1600525 感謝作者??

java中的常見(jiàn)注解

jdk的自帶注解

  • @Override:告訴編譯器我重寫了接口方法
  • @Deprecated:告訴編譯器這個(gè)方法過(guò)時(shí)了,不建議使用,Ide會(huì)在方法上劃?rùn)M線
  • @SuppressWarnings("deprecation"):關(guān)閉方法中出現(xiàn)的警告

下面列出@SuppressWarnings注解參數(shù)的幾個(gè)常見(jiàn)用法

例:@SuppressWarnings(value={ "rawtypes", "unchecked" })
1.deprecation:去除不暫成使用類的警告
2.serial:當(dāng)在可序列化的類上缺少 serialVersionUID 定義時(shí)的警告
3.finally:任何 finally 子句不能正常完成時(shí)的警告
4.rawtypes:去除傳參數(shù)時(shí)也要帶泛型
5.unchecked:執(zhí)行了未檢查的轉(zhuǎn)換時(shí)的警告,例如當(dāng)使用集合時(shí)沒(méi)有用泛型來(lái)指定集合保存的類型
6.unused:去除對(duì)未使用代碼的警告
7:all:去除所有類型的警告

元注解

元注解的作用就是注解其他注解,一般我們使用自定義注解時(shí),就需要用元注解來(lái)標(biāo)注我們自己的注解,一共有以下四個(gè)元注解

1.@Target:說(shuō)明了Annotation被修飾的范圍,可被用于 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構(gòu)造方法、成員變量、枚舉值)、方法參數(shù)和本地變量(如循環(huán)變量、catch參數(shù))。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標(biāo)

例:@Target(ElementType.TYPE)
1.ElementType.CONSTRUCTOR:用于描述構(gòu)造器
2.ElementType.FIELD:用于描述域(類的成員變量)
3.ElementType.LOCAL_VARIABLE:用于描述局部變量(方法內(nèi)部變量)
4.ElementType.METHOD:用于描述方法
5.ElementType.PACKAGE:用于描述包
6.ElementType.PARAMETER:用于描述參數(shù)
7.ElementType.TYPE:用于描述類、接口(包括注解類型) 或enum聲明

2.@Retention:定義了該Annotation被保留的時(shí)間長(zhǎng)短,有些只在源碼中保留,有時(shí)需要編譯成的class中保留,有些需要程序運(yùn)行時(shí)候保留。即描述注解的生命周期

例:@Retention(RetentionPolicy.RUNTIME)
1.RetentionPoicy.SOURCE:在源文件中有效(即源文件保留)
2.RetentionPoicy.CLASS:在class文件中有效(即class保留)
3.RetentionPoicy.RUNTIME:在運(yùn)行時(shí)有效(即運(yùn)行時(shí)保留)

3.@Documented:它是一個(gè)標(biāo)記注解,即沒(méi)有成員的注解,用于描述其它類型的annotation應(yīng)該被作為被標(biāo)注的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化

4.@Inherited:它也是一個(gè)標(biāo)記注解,它的作用是,被它標(biāo)注的類型是可被繼承的,比如一個(gè)class被@Inherited標(biāo)記,那么一個(gè)子類繼承該class后,則這個(gè)annotation將被用于該class的子類。

注意:一個(gè)類型被@Inherited修飾后,類并不從它所實(shí)現(xiàn)的接口繼承annotation,方法并不從它所重載的方法繼承annotation。

自定義注解

自定義注解格式:

public @interface 注解名 {定義體}

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

注解參數(shù)的可支持?jǐn)?shù)據(jù)類型:

1.所有基本數(shù)據(jù)類型(int,float,boolean,byte,double,char,long,short)
2.String類型
3.Class類型
4.enum類型
5.Annotation類型
6.以上所有類型的數(shù)組

定義注解成員的注意點(diǎn): 第一,只能用public或默認(rèn)(default)這兩個(gè)訪問(wèn)權(quán)修飾.例如,String value();這里把方法設(shè)為defaul默認(rèn)類型;

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

第二,參數(shù)成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基本數(shù)據(jù)類型和 String,Enum,Class,annotations等數(shù)據(jù)類型,以及這一些類型的數(shù)組。

//定義一個(gè)枚舉
public enum RequestMethod {
    GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";

    String[] path() default {};

    RequestMethod[] method() default {};//枚舉數(shù)組
}

第三,如果只有一個(gè)參數(shù)成員,最好把參數(shù)名稱設(shè)為"value",后加小括號(hào)。

注解的默認(rèn)值

注解元素必須有確定的值,要么指定時(shí)給默認(rèn)值,要么使用時(shí)給值。不過(guò)有時(shí)候我們需要確定表達(dá)一個(gè)元素不存在值,所以使用空字符串或者負(fù)數(shù)表示某個(gè)元素不存在,在定義注解時(shí),這已經(jīng)成為一個(gè)約定用法。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface User {

    public int id() default -1;
    public String name() default "";
    public String address() default "";
}

對(duì)于@Inherited注解的補(bǔ)充

輸入圖片說(shuō)明

結(jié)論:父類的類上和方法上有自定義注解,并且被@Inherited標(biāo)記,那么子類只有繼承的情況下才會(huì)繼承父類注解。重寫,重載,實(shí)現(xiàn)父類方法這些都不會(huì)繼承父類注解。

自定義注解的使用

java自定義注解

java的注解處理器類主要是AnnotatedElement接口的實(shí)現(xiàn)類實(shí)現(xiàn),為位于java.lang.reflect包下。由下面的class源碼可知AnnotatedElement接口是所有元素的父接口,這時(shí)我們通過(guò)反射獲得一個(gè)類的AnnotatedElement對(duì)象后,就可以通過(guò)下面表格的幾個(gè)方法,訪問(wèn)Annotation信息。

public final class Class<T> implements java.io.Serializable, GenericDeclaration, Type, AnnotatedElement {

總結(jié)AnnotatedElement的常用方法

輸入圖片說(shuō)明

注意:getDeclaredAnnotations和getAnnotations得到的都是當(dāng)前類上面所有的注解(不包括方法上注解和屬性上注解),不同的是,前者不包括繼承的。而getAnnotations得到的是包括繼承的所有注解。

注解處理器使用示例

新建自定注解@ReqMapping

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Description:
 * Created by gaowei on 2018/1/3.
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReqMapping {

    ReqMethod [] method() default {};

    String[] val() default "";
}

新建一個(gè)枚舉類

public enum ReqMethod {
        GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}

新建自定義注解@ReqValue

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Description:
 * Created by gaowei on 2018/1/4.
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReqValue {

    String value1() default "";

    String value2() default "";
}

使用自定義注解

@ReqMapping(method = ReqMethod.POST,val = "類")
public class User  {

    @ReqValue(value1 = "張三")
    private String userName;

    @ReqValue(value2 = "密碼")
    private String pswd;

    @ReqMapping(method = ReqMethod.GET)
    public void get(){

    }

    @ReqMapping(method = ReqMethod.POST)
    public void post(){

    }

    @ReqMapping(val={"a","b"})
    public void other(){

    }

}

注解處理器測(cè)試

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Description:
 * Created by gaowei on 2018/1/2.
 */
public class TestAnnotation {

    public static void main(String[] args) {
        Class<User> clazz = User.class;

        //獲得clazz(User)里面所有方法信息
        Method[] methods = clazz.getDeclaredMethods();

        //獲得clazz(User)里面所有屬性信息
        Field[] declaredFields = clazz.getDeclaredFields();

        System.out.println("methods注解個(gè)數(shù):"+methods.length);
        System.out.println("declaredFields注解個(gè)數(shù):"+declaredFields.length);

        //遍歷循環(huán)所有方法信息
        for (Method method : methods) {
            //判斷method是否含有指定元素的注解
            if (method.isAnnotationPresent(ReqMapping.class)) {
                //返回當(dāng)前方法上的注解對(duì)象
                ReqMapping reqMapping = method.getAnnotation(ReqMapping.class);
                //獲得注解的值
                System.out.println("方法注解值:"+reqMapping.method());

                //如果一個(gè)注解有多個(gè)值,通過(guò)遍歷取出(特別注意:reqMapping.val(),這個(gè)val()是你定義注解的成員)
                String[] values = reqMapping.val();
                for (String value : values) {
                    System.out.println(value);
                }
            }
        }

        //獲得類里面所有方法的注解信息
        for (Field declaredField : declaredFields) {
            if(declaredField.isAnnotationPresent(ReqValue.class)){
                ReqValue reqValue = declaredField.getAnnotation(ReqValue.class);
                System.out.println("屬性注解值:"+reqValue.value1());
                System.out.println("屬性注解值:"+reqValue.value2());
            }
        }

        //獲得類上的所有注解
        Annotation[] declaredAnnotations = clazz.getDeclaredAnnotations();
        for (Annotation declaredAnnotation : declaredAnnotations) {
            System.out.println("類注解值:"+ declaredAnnotation);
        }

    }
}

使用場(chǎng)景:http://www.itdecent.cn/p/a7bedc771204

最后編輯于
?著作權(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)容