Java 注解
今天说一说我们经常用到的 java 注解,java 注解说难吧,也不是很难,说简单吧,我们不经常用的话,对它也就不太熟悉。
看一下自定义一个普通注解的代码:
@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface LoginClient{}
复制代码
这是自定义的一个注解,注解接口有三个注解,这三个注解是什么含义呢?我们依次看一下
@Target
@Target 表示这个注解修饰的对象范围
@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();}
复制代码
有以下范围值,TYPE:作用于类,接口,枚举类,FIELD:作用于域,METHOD:作用于方法,PARAMETER:作用于参数,CONSTRUCTOR:作用于构造器,LOCAL_VARIABLE:作用于局部变量,ANNOTATION_TYPE 作用于注解,PACKAGE 作用于包,TYPE_PARAMETER 作用于普通变量的声明中,TYPE_USE:作用于任何类型的名称。
从以下源码中也可以看到 @Target 的取值
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}
复制代码
@Retention
@Retention 定义注解保留的级别,RUNTIME 表示运行时有效,被编译器记录在类文件中,可以利用反射读取,另外两个 CLASS 表示被编译器记录在类文件中,但是运行时不会被保留,默认是这一个,SOURCE 表示被编译器丢弃,在源文件中保留。
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}
复制代码
@Inherited
@Inherited 表表示被标注的类能被继承,注解作用于子类。
@Documented
@Documented 表示注解可以被 javadoc 类工具文档化
总结
这篇文件简单介绍了一下如何自定义一个注解和注解几个标准元注解,@Target 表示这个注解修饰的对象范围,@Retention 定义注解保留的级别,一般我们使用 RUNTIME,这样可以利用反射获取信息,@Documented 表示能够被工具文档化,也是用到的。
评论