1. Annotation declaration: An annotation can be declared through @interface.
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface BindView { int value(); }
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Get { String value() default ""; }
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Queue { String value() ; }
2. @Target meta-annotation, annotation of annotation, its value is defined in the ElementType enumeration class.
@Target annotation is used to define the location of our custom annotation code.
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) public @interface Target { ElementType[] value(); }
1) ElementType.FIELD is used on member variables.
2) ElementType.METHOD is used on member methods.
3) ElementType.PARAMETER is used on method parameters.
4) ElementType.TYPE is used on classes and interfaces.
5) ElementType.ANNOTATION_TYPE is used in annotations.
3.@Retention meta-annotation, the value is defined in the RetentionPolicy enumeration class.
is used to define the stage in which annotations take effect:
1) SOURCE: Annotations are only valid in the source code stage and will not be compiled into bytecode.
2) CLASS: Annotations are valid in the source code and bytecode stages, but do not exist in the running stage.
3) RUNTIME: Annotations are valid in source code, bytecode, and runtime phases, and are also the most commonly used.
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) public @interface Retention { RetentionPolicy value(); }
public enum RetentionPolicy { SOURCE, CLASS, RUNTIME; private RetentionPolicy() { } }
2. Use of annotations
@BindView(R.id.start_activity) TextView startTextView;
@Get("http://www.baidu.com") Call getPerson(@Queue("name") String name,@Queue("200")int price); @Get("http://www.baidu.com") Call getPerson();
The use of annotations is very simple.
Annotations alone have no meaning and must be used in conjunction with other technologies.
Application:
1) Annotate Apt annotation processor, produce java code, databinding, butterknife, dagger2 hilt
2) Annotation code burying point
3) Annotate reflection dynamic proxy retrofit xUtils lifecycle
The above is the detailed content of How to declare Java meta-annotation Retention. For more information, please follow other related articles on the PHP Chinese website!