如果用最简单的话描述注解,那就是元数据,即一种描述数据的数据。所以,可以说注解就是源代码的元数据。
在Java中叫Annotation,Annotation是一种应用于类、方法、参数、变量、构造器及包声明中的特殊修饰符。
Java自带的注解有@Override,@Supperwarning,@Deprecated
1.注解的作用
1.生成文档,比如@see @param @return
2.在编译时进行格式检查。如@override 放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出
3.追踪代码依赖性,实现替代配置文件,比如Spring的各种注解等
2.如何实现一个自定义注解
我们先写一个最简单的注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionDesc {
}
上面这个注解没有任何的属性定义,我们看下定义一个注解所需的元素。首先使用关键字“@interface” 表明这类是注解类;然后这类上加上注解“@Retention”,这是定义注解所必须的。
注解元素
@Retention是注解的注解,称为元注解。我们看一下@Retention的内部:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
我们看到Retention本身也被@Retention注解,还有@Documented和@Target(ElementType.ANNOTATION_TYPE),ANNOTATION_TYPE表明这个注解应应用在注解上。
Retention有一个属性value,类型为枚举的RetentionPolicy,它没有默认值,所以不写这个值就会报错,我们继续看一下RetentionPolicy:
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