@[toc]
1. Custom annotation format
Annotations are defined as public because they are intended for use in other classes
The type supported by the annotation attribute
- All basic data types 8
- Type String
- The Class type
- Enum type
- The Annotation type
- All types of data above
Annotations cannot directly inherit from other annotations.
2. Custom annotation demo
Customize a person’s description annotations
// This annotation applies to a member variable
@Target(ElementType.FIELD)
// The lifecycle of this annotation is runtime, and information can be retrieved through reflection
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonInfoAnnotation {
/ / name
public String name(a);
public int age(a) default 19;
public String gender(a) default"Male";
// The development language
public String[] language();
}
Copy the code
Custom notes for a course information description
// This annotation applies to classes and methods
@Target({ElementType.TYPE, ElementType.METHOD})
// The lifecycle of this annotation is runtime, and information can be retrieved through reflection
@Retention(RetentionPolicy.RUNTIME)
public @interface CourseInfoAnnotation {
// Course name
public String courseName(a);
// Course tag
public String courseTag(a);
// Course introduction
public String courseProfile(a);
// Course number
public int courseIndex(a) default 101;
}
Copy the code
Define a class, MyCourse, with annotations describing information about it
package demo.annotation;
/** * MyCourse **@author: https://javaweixin6.blog.csdn.net/ * creation time: 2021/2/21 13:49 * Version 1.0 * /
CourseInfoAnnotation(courseName = "Java annotation learning ", courseTag = "annotation ", courseProfile =" Zero-based annotation development ")
public class MyCourse {
@personInfoannotation (name = "jay write code ", language = {" Java ", "javaScript"})
private String author;
CourseInfoAnnotation(courseName = "Java multithreading to learn ", courseTag =" Multithreading ", courseProfile = "From 0 to learn multithreading ", courseIndex = 666)
public void getCourseInfo(a){}}Copy the code
Run the getCourseInfo method from the class above
public class AnnotationDemo {
public static void main(String[] args) {
MyCourse myCourse = new MyCourse();
myCourse.getCourseInfo();
System.out.println("Execution completed"); }}Copy the code
As the result of the execution is shown below, you can see that the annotation does not affect the relevant code execution of its Java class.
The relationship between annotations and classes
You can see below that the Class Class implements the AnnotatedElement interface. The AnnotatedElement interface is an annotation-related interface.AnnotatedElement is a top AnnotatedElement interface. The classes associated with reflection, field. Method, and Constructor essentially implement AnnotatedElementThere are three common methods for this interface.getAnnotation(Class<T> annotationClass)
Gets an annotation, including inherited annotationsAnnotation[] getAnnotations();
Get all annotations, including inherited onesdefault boolean isAnnotationPresent
Used to determine whether the specified annotation element is included, returning true if it is, false if not.
Parse the annotated information
4.1 Parsing annotation information in a class
Create an AnnotationParser class that parses the annotated information. The following code. Parses the information from the CourseInfoAnnotation annotation annotation on the MyCourse class in the steps above.
public class AnnotationParser {
public static final String enterStr = "\n";
// Parse annotation information on the class
public static void parseTypeAnnotation(a) {
Class<MyCourse> clazz = MyCourse.class;
// Get the annotation information on the class
Annotation[] annotations = clazz.getAnnotations();
// Iterate over all the annotations on the page
for (Annotation annotation : annotations) {
// annotations are cast
CourseInfoAnnotation courseInfoAnnotation = (CourseInfoAnnotation) annotation;
// Retrieve information about annotations one by one
System.out.println(Course Name: + courseInfoAnnotation.courseName() + enterStr +
"Course Label:" + courseInfoAnnotation.courseTag() + enterStr +
"Course Description:" + courseInfoAnnotation.courseProfile() + enterStr +
"Course Number:"+ courseInfoAnnotation.courseIndex()); }}public static void main(String[] args) { parseTypeAnnotation(); }}Copy the code
The following print indicates that the annotation information on its class was successfully parsed.
4.2 Parsing annotation information on member variables
public static final String enterStr = "\n";
// Parse annotation information on member variables
public static void parseFieldAnnotation(a) {
Class<MyCourse> clazz = MyCourse.class;
// Get all member variables
Field[] fields = clazz.getDeclaredFields();
// Iterate over all member variables
for (Field field : fields) {
// Determine if there is an annotation of the specified type in a member variable
boolean isAnnotationPresent = field.isAnnotationPresent(PersonInfoAnnotation.class);
if (isAnnotationPresent) {
PersonInfoAnnotation personInfoAnnotation = field.getAnnotation(PersonInfoAnnotation.class);
System.out.println("Name:" + personInfoAnnotation.name() + enterStr +
"Age:" + personInfoAnnotation.age() + enterStr +
"Gender: + personInfoAnnotation.gender() + enterStr);
String[] languages = personInfoAnnotation.language();
for (String language : languages) {
System.out.println(Course Name:+ language); }}}}public static void main(String[] args) {
parseFieldAnnotation();
}
Copy the code
You can see from the above image that the annotation successfully parsed the information on the member variable. Default values for age and gender.
4.3 Parsing annotation information on methods
public static final String enterStr = "\n";
// Parse annotation information on methods
public static void parseMethodAnnotation(a) {
Class<MyCourse> clazz = MyCourse.class;
// Get all the methods
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
boolean isAnnotationPresent = method.isAnnotationPresent(CourseInfoAnnotation.class);
// Determine if there are specific annotations
if (isAnnotationPresent) {
// cast to specific annotations
CourseInfoAnnotation courseInfoAnnotation = method.getAnnotation(CourseInfoAnnotation.class);
System.out.println(Course Name:+courseInfoAnnotation.courseName()+enterStr+
"Course Label:"+courseInfoAnnotation.courseTag()+enterStr+
"Course Description:"+courseInfoAnnotation.courseProfile()+enterStr+
"Course Number:"+courseInfoAnnotation.courseIndex()+enterStr); }}}public static void main(String[] args) {
parseMethodAnnotation();
}
Copy the code
The result is printed as followsYou can see in the figure below that the annotation information on the method was successfully obtained.
When changing Retention in the annotation from RUNTIME to CLASS or SOURCE, as shown in the figure belowRepeat the above method to get annotation information. The result is shown in the figure below, which gets blank information, so if you want to get the information in annotation, you need to use RUNTIME