Click to enter _ more _java thousand ask color= "#ff0000"
1. How to customize annotations
To learn to use annotations, we need to understand annotations and understand common annotations provided by Java. More importantly, learn to customize annotations.
See the comments here: what is the comment
Our custom annotations require the use of the @interface keyword, with the following syntax:
public @interface 注解名 {定义体} default {默认值}
When you use @interface to customize annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces.
@interface is used to declare an annotation, in which each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter. The default value of the parameter is declared through default, and if default is not specified, the parameter is required.
The annotation parameter (the return value of the annotation method) can be decorated only with public or default access rights, and only the following data types are supported:
- All basic data Types (Int,float,boolean,byte,double,char,long,short)
- String type
- Class type
- Enum type
- Annotation type
- Arrays of all types above
We typically use reflection to get annotations, a simple custom annotation, and an example of using annotations:
Annotation class:
@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation { default"";}
Annotated class:
publicclass TestInfo { @TestAnnotation"公司名称") private String company; @TestAnnotation"职位") private String position;}
Use annotations:
publicclass TestMain { publicstaticvoidmain(String[] args) { Field[] fields = TestInfo.class.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(TestAnnotation.class)) { TestAnnotation testAnnotation = (TestAnnotation) field.getAnnotation(TestAnnotation.class); System.out.println("field:"", annotation:" + testAnnotation.name()); } } }}
We run the following results as follows:
field:company, annotation:公司名称
field:position, annotation:职位
Note @retention (retentionpolicy.runtime) in the annotation class is the annotation used to decorate the annotations, the meta-annotations, used to describe and qualify the usage scenarios and constraints of the custom annotations. Specific as follows:
Understanding meta-Annotations look here: [meta-annotations are what][3]
[3]:
Java thousand ask _03 Basic grammar (021) _ How to customize annotations