Java注解的使用方法与原理
1.什么是注解
例如我们常见的@Override,注解用于对代码进行说明,可以对包、类、接口、字段、方法参数、局部变量等进行注解
一般常用的注解可以分为三类:
-
一类是Java自带的标准注解,包括@Override(标明重写某个方法)、@Deprecated(标明某个类或方法过时)和@SuppressWarnings(标明要忽略的警告),使用这些注解后编译器就会进行检查。
-
一类为元注解,元注解是用于定义注解的注解,包括@Retention(标明注解被保留的阶段)、@Target(标明注解使用的范围)、@Inherited(标明注解可继承)、@Documented(标明是否生成javadoc文档)
-
一类为自定义注解,可以根据自己的需求定义注解
2.注解使用演示
这边总共定义了4个注解来演示注解的使用
定义一个可以注解在Class,interface,enum上的注解,
定义一个可以注解在METHOD上的注解
定义一个可以注解在FIELD上的注解
定义一个可以注解在PARAMETER上的注解
具体代码如下:
/**
* 定义一个可以注解在Class,interface,enum上的注解
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnTargetType {
/**
* 定义注解的一个元素 并给定默认值
* @return
*/
String value() default "我是定义在类接口枚举类上的注解元素value的默认值";
}
/**
* 定义一个可以注解在METHOD上的注解
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnTargetMethod {
/**
* 定义注解的一个元素 并给定默认值
* @return
*/
String value() default "我是定义在方法上的注解元素value的默认值";
}
/**
* 定义一个可以注解在FIELD上的注解
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnTargetField {
/**
* 定义注解的一个元素 并给定默认值
* @return
*/
String value() default "我是定义在字段上的注解元素value的默认值";
}
/**
* 定义一个可以注解在PARAMETER上的注解
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnTargetParameter {
/**
* 定义注解的一个元素 并给定默认值
* @return
*/
String value() default "我是定义在参数上的注解元素value的默认值";
}
编写一个测试处理类处理以上注解
@MyAnTargetType
public class AnnotationTest {
@MyAnTargetField
private String field = "我是字段";
@MyAnTargetMethod("测试方法")
public void test(@MyAnTargetParameter String args) {
System.out.println("参数值 === "+args);
}
public static void main(String[] args) {
// 获取类上的注解MyAnTargetType
MyAnTargetType t = AnnotationTest.class.getAnnotation(MyAnTargetType.class);
System.out.println("类上的注解值 === "+t.value());
MyAnTargetMethod tm = null;
try {
// 根据反射获取AnnotationTest类上的test方法
Method method = AnnotationTest.class.getDeclaredMethod("test",String.class);
// 获取方法上的注解MyAnTargetMethod
tm = method.getAnnotation(MyAnTargetMethod.class);
System.out.println("方法上的注解值 === "+tm.value());
// 获取方法上的所有参数注解 循环所有注解找到MyAnTargetParameter注解
Annotation[][] annotations = method.getParameterAnnotations();
for(Annotation[] tt : annotations){
for(Annotation t1:tt){
if(t1 instanceof MyAnTargetParameter){
System.out.println("参数上的注解值 === "+((MyAnTargetParameter) t1).value());
}
}
}
method.invoke(new AnnotationTest(), "改变默认参数");
// 获取AnnotationTest类上字段field的注解MyAnTargetField
MyAnTargetField fieldAn = AnnotationTest.class.getDeclaredField("field").getAnnotation(MyAnTargetField.class);
System.out.println("字段上的注解值 === "+fieldAn.value());
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果如下:
类上的注解值 === 我是定义在类接口枚举类上的注解元素value的默认值
参数上的注解值 === 我是定义在参数上的注解元素value的默认值
参数值 === 改变默认参数
方法上的注解值 === 测试方法
字段上的注解值 === 我是定义在字段上的注解元素value的默认值
3.注解的实现原理
以上只抽取了注解的其中几种类型演示,下面让我们一起来看看他们是怎么工作的
让我们先看一下实现注解三要素:
-
1,注解声明
-
2,使用注解的元素
-
3,操作注解使其起作用(注解处理器)
注解声明
首先我们让看一下java中的元注解(也就是上面提到的注解的注解),总共有4个如下:
@Target
@Retention
@Documented
@Inherited
这4个元注解都是在jdk的java.lang.annotation包下面
@Target
Target说明的是Annotation所修饰的对象范围,源码如下:
@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();
}
其中只有一个元素ElementType,再看看它的源码如下:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
ElementType是一个枚举类定义注解可以作用的类型上,上面例子中演示了TYPE,FIELD,METHOD,PARAMETER 4种可以作用的目标
@Retention
定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个元注解可以对 Annotation的“生命周期”限制
@Documented
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员
@Inherited
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类
注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。
当@Inherited annotation类型标注的annotation的Retention是RetentionPolicy.RUNTIME,则反射API增强了这种继承性。如果我们使用java.lang.reflect去查询一个@Inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。
注解处理器
这个是注解使用的核心了,前面我们说了那么多注解相关的,那到底java是如何去处理这些注解的呢
从getAnnotation进去可以看到java.lang.class实现了AnnotatedElement方法
MyAnTargetType t = AnnotationTest.class.getAnnotation(MyAnTargetType.class);
public final class Class<T> implements java.io.Serializable,
GenericDeclaration,
Type,
AnnotatedElement
java.lang.reflect.AnnotatedElement 接口是所有程序元素(Class、Method和Constructor)的父接口,所以程序通过反射获取了某个类的AnnotatedElement对象之后,程序就可以调用该对象的如下四个个方法来访问Annotation信息:
-
方法1:
T getAnnotation(Class annotationClass): 返回改程序元素上存在的、指定类型的注解,如果该类型注解不存在,则返回null。 -
方法2:Annotation[] getAnnotations():返回该程序元素上存在的所有注解。
-
方法3:boolean is AnnotationPresent(Class<?extends Annotation> annotationClass):判断该程序元素上是否包含指定类型的注解,存在则返回true,否则返回false.
-
方法4:Annotation[] getDeclaredAnnotations():返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响
posted on 2021-08-29 23:05 专吃有AB血型的公老鼠 阅读(443) 评论(0) 编辑 收藏 举报