java注解基础

一:元注解

元注解的作用就是负责注解其他注解

1.@Target

说明:
用来指明注解所修饰的目标,包括packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)

取值:

作用 英文描述
CONSTRUCTOR 用于描述构造器
FIELD 用于描述域 (类的成员变量) Field declaration.
LOCAL_VARIABLE 用于描述局部变量 Local variable declaration.
METHOD 用于描述方法 Method declaration.
PACKAGE 用于描述包 Package declaration.
PARAMETER 用于描述参数 Parameter declaration.
TYPE 用于描述类、接口(包括注解类型) 或enum声明 Class, interface or enum declaration.
CONSTRUCTOR 构造器描述 Constructor declaration.
ANNOTATION_TYPE 注解类型描述 Annotation type declaration.

对应代码:

public enum ElementType {
    /**
     * Class, interface or enum declaration.
     */
    TYPE,
    /**
     * Field declaration.
     */
    FIELD,
    /**
     * Method declaration.
     */
    METHOD,
    /**
     * Parameter declaration.
     */
    PARAMETER,
    /**
     * Constructor declaration.
     */
    CONSTRUCTOR,
    /**
     * Local variable declaration.
     */
    LOCAL_VARIABLE,
    /**
     * Annotation type declaration.
     */
    ANNOTATION_TYPE,
    /**
     * Package declaration.
     */
    PACKAGE
}

举例一:

Target(ElementType.TYPE)
public @interface AnnotationTest1 {
    public String tableName() default "className";
}

小结:
说明这个注解被用来注解

  • 接口(包括注解类型的接口)
  • enum

举例二:

@Target(ElementType.FIELD)
public @interface AnnotationTest2 {
}

小结:
说明这个注解被用来注解

  • 类的成员变量
2.@Retention

说明:
该注解定义了该Annotation的生命周期某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取。

取值:

作用 英文描述
SOURCE 在源文件中有效(即源文件保留) Annotation is only available in the source code.
CLASS 在class文件&源文件中有效(即class保留) Annotation is available in the source code and in the class file, but nott runtime. This is the default policy.
RUNTIME 在运行时&源文件&class文件有效(即运行时保留) Annotation is available in the source code, the class file and is available at runtime.

对应代码:

public enum RetentionPolicy {
    /**
     * Annotation is only available in the source code.
     */
    SOURCE,
    /**
     * Annotation is available in the source code and in the class file, but not
     * at runtime. This is the default policy.
     */
    CLASS,
    /**
     * Annotation is available in the source code, the class file and is
     * available at runtime.
     */
    RUNTIME
}

举例一:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    public String name() default "fieldName";
    public String setFuncName() default "setField";
    public String getFuncName() default "getField"; 
    public boolean defaultDBValue() default false;
}

小结:

  1. 这个注解被用来描述类的成员变量
  2. 并且注解一直保留到运行时
3.@Documented

说明:
@Documented的作用是在生成javadoc文档的时候将该Annotation也写入到文档中。

举例一:

@Target(ElementType.METHOD)
@Documented  
public @interface DocumentTest {   
    String hello();   
} 

使用:

public class DocumentClass {   
    /**  
     * this is method of doSomething  
     */  
    @DocumentTest(hello = "yahaitt")   
    public void doSomething() {   
        System.out.println("do something");   
    }   
} 

结果:

@DocumentTest(hello="yahaitt")
public void doSomething()
this is method of doSomething  

4.@Inherited

说明:用在注解的继承,我们自定义注解(Annotation)时,把自定义的注解标注在父类上,但是它不会被子类所继承,我们可以在定义注解时给我们自定义的注解标注一个@Inherited注解来实现注解继承。

举例一:

@Retention(RetentionPolicy.RUNTIME)  
@Inherited  
public @interface InheritedTest {  
    String value();  
} 
@InheritedTest("Jadyer")  
public class Parent {  
    @InheritedTest("JavaEE")  
    public void doSomething() {  
        System.out.println("Parent do something");  
    }  
}
public class Child extends Parent {  

}

测试:

public class Test {  
    public static void main(String[] args) throws SecurityException, NoSuchMethodException {  
        classTest();  
        methodTest();  
    }  

    /** 
     * 通过反射方式测试子类是否会继承父类中定义在类上面的注解 
     */  
    public static void classTest(){  
        Class<Child> c = Child.class; //获取Child的Class对象
        if (c.isAnnotationPresent(InheritedTest.class)) { //判断InheritedTest类是不是Child的父注解类
            InheritedTest inheritedTest = c.getAnnotation(InheritedTest.class);  
            String value = inheritedTest.value();  
            System.out.println(value);  
        }  
    }  

    /** 
     * 通过反射方式测试子类是否会继承父类中定义在方法上面的注解 
     */  
    public static void methodTest() throws SecurityException, NoSuchMethodException{  
        Class<Child> c = Child.class;  
        Method method = c.getMethod("doSomething", new Class[]{});  

        if (method.isAnnotationPresent(InheritedTest.class)) {  
            InheritedTest inheritedTest = method.getAnnotation(InheritedTest.class);  
            String value = inheritedTest.value();  
            System.out.println(value);  
        }  
    }  
}

结果:

  • 如果父类的注解是定义在类上面,那么子类是可以继承过来的
  • 如果父类的注解定义在方法上面,那么子类仍然可以继承过来
  • ++如果子类重写了父类中定义了注解的方法,那么子类将无法继承该方法的注解++

二:Java内建注解

Java提供了三种内建注解

  • @Override——当我们想要复写父类中的方法时,我们需要使用该注解去告知编译器我们想要复写这个方法。这样一来当父类中的方法移除或者发生更改时编译器将提示错误信息。
  • @Deprecated——当我们希望编译器知道某一方法不建议使用时,我们应该使用这个注解。Java在javadoc 中推荐使用该注解,我们应该提供为什么该方法不推荐使用以及替代的方法。
  • @SuppressWarnings——这个仅仅是告诉编译器忽略特定的警告信息,例如在泛型中使用原生数据类型。它的保留策略是SOURCE并且被编译器丢弃。

三:自定义注解

使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。

格式:

public @interface 注解名 {
    定义体
} 

注解参数支持的数据类型

  • 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
  • String类型
  • Class类型
  • enum类型
  • Annotation类型
  • 以上所有类型的数组

参数的设定

  • 只能用public和default修饰
  • 参数成员只能用上面说明的数据类型
  • 如果只有一个参数成员,最好把参数名称设为”value”,后加小括号 (比如:public String[] value();)
  • 可以在使用default为每个参数设置一个默认值。注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定,非基本类型的注解元素的值不可为null。因此, 使用空字符串或0作为默认值是一种常用的做法。(String date() default "";)

举例一:

@Target(ElementType.FIELD)//用于描述类的字段
@Retention(RetentionPolicy.RUNTIME)//保留到运行时
@Documented//打印文档时显示
public @interface FruitName {
    String value() default "";//默认值是""
}

举例二:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    public enum Color{ BULE,RED,GREEN};//声明颜色枚举
    Color fruitColor() default Color.GREEN;
}

举例三:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
     public int id() default -1;

     public String name() default "";

     public String address() default "";
}

使用:

public class Apple {
    @FruitName("Apple")
    private String appleName;
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
}

四:注解的处理

Java在java.lang.reflect 包下新增了AnnotatedElement接口,该接口主要有如下几个实现类:
[图片上传失败...(image-295d0f-1520831478367)]

  • Class:类定义
  • Constructor:构造器定义
  • Field:累的成员变量定义
  • Method:类的方法定义
  • Package:类的包定义

所以这些我们经常用的反射手段所用到的类,都实现了AnnotatedElement接口,既然实现了此接口,那么一定有对应的实现方法供我们调用。

//如果存在这样的注解,则返回该元素的指定类型的注解,否则为空。
<T extends Annotation> T getAnnotation(Class<T> annotationClass)
//返回该程序元素上存在的所有注解。
Annotation[] getAnnotations()
//判断该程序元素上是否包含指定类型的注解,存在则返回true,否则返回false.
boolean is AnnotationPresent(Class<?extends Annotation> annotationClass)
//返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。
Annotation[] getDeclaredAnnotations()

可以看到通过反射使用的类,都可以通过指定接口得到在上面注册的注解。所以我们只需要反射得到Class、Method和Constructor,因为AnnotatedElement是Class、Method和Constructor的父接口,它们都实现了AnnotatedElement,所以,在Class、Method和Constructor中就可以使用AnnotatedElement中声明的方法来得到注解和注解内容。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容