1前言
我们在使用框架时经常会使用到各种注解 如 SpringBootApplication,RequestMapping,RestController等,JDK中也有一些经常用到的注解,比如大家都比较熟悉的 Override。对于注解,我们一般都是只要知道怎么用就行了,比如加上注解完成了什么功能,达到了什么效果。但是今天我这个小白就好奇,为啥加上一个这样的注解就能达到某个功能呢。接下来我将解开注解的迷雾。
2注解的基础
2.1注解的概念
Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制,是一种代码级别的说明。Java 语言中的类、方法、变量、参数和包等都可以被标注。
一个注解准确意义上来说,只不过是一种特殊的注释而已,如果没有解析它的代码,它可能连注释都不如。
简单一句话:就是给计算机(编译器)看的注释。
2.2注解的作用
编译检查:通过代码里标识的注解让编译器能够实现基本的编译检查【Override】
编写文档:通过代码里标识的注解生成文档【生成文档doc文档】,API文档是通过抽取代码中的文档注释生成的。
替代配置文件
2.3注解的格式
public @interface 注解名称{}
// jdk ovrride 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
2.4注解的本质
//继承 java.lang.annotation.Annotation 的接口
public @interface Check {
}
// 反汇编
public interface Check extendsjava.lang.annotation.Annotation {
}
2.5注解的属性
注解其实就是继承 Annotation的接口,那注解的属性同样可以理解为接口中可以定义的抽象方法。
属性的返回值类型只能为以下几种:
基本数据类型
String
枚举
注解
以上类型的数组
public @interface Check {
String className();
String methodName() default "hello";
}
// 使用时候必须给属性赋值,如果定义的时候给了默认值就可以不重新赋值。如果只有一个属性 value,可以省略 value =
@Check(className = "xxx", methodName = "yyy")
void Test() {}
2.6 元注解
用于描述注解的注解
@Target:描述能够作用的位置
其中value中ElementType取值可以有以下几种情况:
TYPE:可以作用在类上
METHOD:可以作用在方法上
FIELD:可以作用于成员变量上
@Retention:描述注解被保留的阶段
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
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 need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented:描述该注解是否会被抽取到api文档中
@Inherited:描述注解是否被子类继承
3 实战
下面两个实战在该博客中有详细描述和实现,值得一看,对注解有更深入的认识。
(5条消息) 【Java基础】 注解_编程芝士的博客-CSDN博客
3.1 取代配置文件
3.2自定义注解
测试框架,check注解。自定义注解,并通过自实现解析代码来完成注解的功能。
4参考及推荐
比较优秀的两篇博客
(5条消息) 【Java基础】 注解_编程芝士的博客-CSDN博客
(5条消息) 【Java基础】 注解_编程芝士的博客-CSDN博客
优秀学习视频: