注解

注解

一.认识注解

注解 

1注解(Annotation):Java5开始,Java对元数据开始支持,就是这里的注解

注解是来自java.lang.annotation.Annotation,

自定义的注解是实现了该接口的,所以所有的注解都是特殊的接口

枚举是特殊的类

 

2注解,Annotation,标签指的是相同的事物

 

3使用注解需要三方面参与才有意义:

1.有一个注解

2.要有别贴的程序元素(,方法,字段)

3.第三方程序赋予注解特殊的含义

 

二.JDK中的注解

JDK内置的注解:Java为我们定义好的注解

[email protected] 限定覆写父类方法

 

[email protected]  标记已过时的成员,不推荐使用.

    注解是从Java5开始的,Date中很多成员都是从JDK1.1就已经过时了,在这个时候是如何来表示过时的成员?

Java5之前是使用文档注释来标识过时的成员

/**

*@Deprecated

[email protected]  抑制编译器发出的警告

只是抑制编译器发出的警告,但是问题任然存在

@SuppressWarnings({ "all" }):抑制所有类型的警告

 

[email protected]  抑制堆污染警告(Java7开始出现的)

堆污染:当一个方法中使用了可变参数和泛型,可能出现该警告

  

三.JDK内置的元注解

元注解:注解的注解

注解:用来表示程序元素

 

@Target:  表示注解可以贴在哪些位置(,方法上,构造器上等等).

位置的常量封装在ElementType枚举类中:

ElementType.ANNOTATION_TYPE只能修饰Annotation

ElementType.CONSTRUCTOR只能修饰构造方法

ElementType.FIELD只能修饰字段(属性),包括枚举常量

ElementType.LOCAL_VARIABLE只能修饰局部变量

ElementType.METHOD只能修饰方法

ElementType.PACKAGE只能修饰包(极少使用)

ElementType.PARAMETER只能修饰参数

ElementType.TYPE只能修饰类,接口,枚举

 

@Retention:  表示注解可以保存在哪一个时期.

     保存的时期的值,封装在RetentionPolicy枚举类中

CLASS 

     编译器将把注释记录在类文件中,但在运行时 VM 不需要保留注释。 

RUNTIME 

     编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。 

SOURCE 

          编译器要丢弃的注释 

注意:以后我们自定义的注解,应该保存到哪个时期?--->RUNTIME

 

@Documented:  使用@Documented标注的标签会保存到API文档中.

@Inherited:   @Inherited标注的标签可以被子类集成到.


@Inherited

public @inteface MyAnn{}

 

@MyAnn

public class A{}

public class B extends A{}

 

四.自定义注解

1.定义注解使用@interface

 

@Target({ElementType中的元素})

@Retention(RetentionPolicy.RUNTIME)

public @interface 注解名称{

    String name() default "lucy";//在注解中称之为属性,元素

    int age() default 12;

    String value();//属性名是value的时候,那么在使用的时候,如果只指定value的值,那么属性名可以省略,直接写属性值

}

Invalid type Integer for the annotation attribute MyAnno.age; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimensional arrays thereof

注解中的属性的类型只能是  基本数据类型 ,    String,         Class,      annotation,   枚举,   一维数组

注解 

 

2.使用注解:

@注解名词,但是只能贴在哪里收到Taget里面定义内容的限制。@Test

---------------------------------------------------------------------------

3.获取注解:

因为在类上,方法上,字段都可能会有注解,那么在这些成员上面就应该有操作注解的方法

Class:

boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Method:

<T extends Annotation>  T  getAnnotation(Class<T> annotationClass) 

Field:

<T extends Annotation> T  getAnnotation(Class<T> annotationClass)  

 

 其实我们大多数时候都是使用别人定义好的注解,自己动手定义注解的机会相对比较少。注解在一些框架中应用的比较多,比如:Junit4

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


转载于:https://my.oschina.net/byronhs/blog/640420