1. Annotation definition
Annotations, also known as metadata, provide a formal way for us to add information to source code, allowing us to read useful information when needed
2. Meta annotations
Meta-annotations are annotations that have been defined by JDK . There are four standard meta-annotations defined by JDK :
|
definition |
value |
|
@Target |
Indicates the scope of the object modified by Annotation |
ElementType: 1. CONSTRUCTOR: used to describe the constructor 2.FIELD: used to describe the domain 3.LOCAL_VARIABLE: used to describe local variables 4.METHOD: Used to describe the method 5.PACKAGE: used to describe the package 6.PARAMETER: used to describe parameters 7.TYPE: Used to describe classes, interfaces ( including annotation types ) or enum declarations |
@Target(ElementType.TYPE) public @interface Table { public String tableName() default "className"; }
|
@Retention |
Defines the length of time the Annotation is retained |
RetentionPoicy: 1. SOURCE: Valid in the source file (that is, the source file is retained) 2. CLASS: Valid in class files (ie class reservation) 3.RUNTIME: Valid at runtime (that is, reserved at runtime) |
|
@Documented |
A public API for describing other types of annotations that should be used as annotated program members , and thus can be documented by tools such as javadoc |
is a markup annotation with no members |
|
@Inherited |
Explains that an annotated type is inherited. If an annotation type modified with @Inherited is used in a class , the annotation will be used in subclasses of that class |
is a markup annotation with no members |
|
3. Custom annotations
@interface is used to declare an annotation, each of which actually declares a configuration parameter ;
The name of the method ;
The return value type is the type of the parameter (the return value type can only be basic types, Class , String , enum ) ;
The default value of a parameter can be declared by default .
Example 1: (The annotation of a single parameter is generally named value , and the method of nama=XXX is not used when using it )
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documentedpublic @interface FruitName {
String value() default "";
}
Example two:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
publicenum Color{ BULE,RED,GREEN};
Color fruitColor() default Color.GREEN;
}
4.通过反射获取注解信息
(注意,只有RetentionPoicy=RUNTIME的时候才能通过反射获取到)
//判断该方法是否包含MyAnnotation注解
method.isAnnotationPresent(MyAnnotation.class)
//获取该方法的MyAnnotation注解实例
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
//获取myAnnotation属性值
String[] value1 = myAnnotation.value1();
//获取方法上的所有注解
Annotation[] annotations = method.getAnnotations();