Understand java annotations and java annotations
The annotation is similar to the following:
Annotations can be used on classes, member variables, and methods.
Assume that two annotations are as follows: (Author and Date)
The two annotations are defined as follows:
Author annotation:
Date annotation:
We can see that the annotation definition is similar to the interface definition, while the Author annotation has the name attribute. Therefore, you must enter the name attribute value when using Author.
If you want the annotation to have a default value, you can do this:
In this way, you do not need to enter the age attribute value when using the Author annotation. If an annotation has multiple attribute values, use commas to separate them.
If only one attribute is defined in the annotation and its name is value, the name can be omitted during use, as shown in the following code:
Annotation is also a type. Since it can be defined, it can also be obtained, like this:
Run the command and you will find that an error is reported. Is it because the code is wrong? Actually, it is not because the annotation retention policy has not been changed.
Next we will talk about the meta annotation. The Meta annotation is the Annotation on the annotation type. Let's take a look at the annotation @ Override's meta annotation.
@ Target and @ Retention are meta annotations, where @ Target indicates the application scope of the annotation and @ Retention indicates the annotation Retention policy.
The two annotations can be viewed based on the java. lang. annotation interface.
java.lang.annotation.RetentionPolicy
Therefore, you only need to set the value of @ Retention to RUNTIME to read the annotation. Its default value is CLASS.
java.lang.annotation.ElementType
@ Target the default value should be all of this (I didn't try it)
You should know how to solve the problem reported just now.
You only need to add the meta annotation @ Retention to the custom annotation. Of course, you can also set the annotation @ Target, just like this:
Author annotation:
Date annotation:
Run the command again to get the result.
In addition, the inheritance of annotation just mentioned also uses the meta annotation: @ Inherited
The annotation does not inherit by default, but this inheritance is also limited.
@ Inherited // indicates whether the annotation can be Inherited. It can only be applied to classes and only valid for class inheritance. It is invalid for the Implemented interfaces.
Annotations may not be used much, but understanding annotations can help us better understand some things. Compare springmvc annotations