注解
自定义注解
格式
public @interface 注解名{
//注解属性
}
- 注解的属性必须要有(),例如String value();
- 注解使用的时候属性必须赋值,除非由默认值
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V4x18D18-1600749369022)(
)]
-
注解的特殊属性:value
value属性如果只有一个value的情况下,value可以省略不写
如果由多个属性,且多个属性没有默认值,value不能省略
元注解
元注解是用来注解自定义注解的
-
@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 用来标注注解的生命周期
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 }
注解的解析
与注解相关的接口
-
Annotation 注解类型,该类是所有注解的父类
-
AnnotatedElement:该接口定义了与注解解析相关的接口
所有的类成分Class,Method,Filed,Constructor都实现了该接口
他们拥有的解析注解的能力:
-
Annotation[] getDeclaredAnnotation();
-
T getDeclaredAnnotation(Class annotationClass)
有的解析注解的能力: -
Annotation[] getDeclaredAnnotation();
-
T getDeclaredAnnotation(Class annotationClass)
-
boolean isAnnotationPresent(Class annotationClass)
-