Explain the implementation and use of Java annotations in detail

Explain the implementation and use of Java annotations in detail

Java annotations are released in Java 5. Their function is to save configuration files and enhance code readability. It is very common in today's various frameworks and development. It is hereby explained.

How to create an annotation

Each custom annotation consists of four meta annotations provided by Java itself:

@Target(ElementType.**)

This is an enumeration. Its top is where the user-defined annotation is used, such as classes, variables, methods, etc

@Retention (retention policy. * *) is used to indicate the level at which annotations are saved, such as at compile time, in class files, and during VM operation

@Documented includes this annotation in Javadoc, which means that this annotation will be extracted into a document by Javadoc tools. The content in the doc document will vary depending on the information content of this annotation

@Inherited: after you define the annotation and use it on the program code, by default, the annotation in the upper parent class will not be inherited into the sub class. You can add Java. Java when defining the annotation lang.annotation. Inherited qualified annotation, which allows the annotation type you define to be inherited.

Talk is heap, show your code

Above, I have defined three annotations, namely, annotations at three levels: common classes, variables and methods.

Next, I define a class that uses these three annotations

The following is how to use this annotation. Annotation extraction is to obtain the corresponding variables and methods through class reflection, and obtain annotations from variables and methods.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>