Overview
Java in the 1.5 version of the introduction of annotation annotation, also known as Java Annotations, annotation is a syntax metadata, can be directly used in the source code, class/Method/variable/parameter/package name can be annotated. Unlike Javadoc tags, the compiler retains the annotation code when generating the class file, while the Java virtual Opportunity retains the annotations in order to use annotations while the program is running (run-time). This allows you to get information about the annotation annotation through reflection.
Built-in annotations
In fact, we often encounter annotations, such as @override, @Deprecated, and so on, these are the JDK built-in annotations, first look at the Java built-in annotations are mainly.
• Annotations that act on Java code
◦ @Override Check whether a method is a replication method, if the method is not found in the parent class or the implemented interface, the compilation will be faulted.
◦ @Deprecated mark a method or a class is discarded, and if the class or method is used, the compilation will report a warning
◦ @SuppressWarnings notifies the compiler to ignore warnings about the parameters being annotated
◦ @SafeVarargs Ignore warnings about calling methods or constructors that contain generic parameters, 1.7 add annotations
◦ @FunctionalInterface indicate that one of the declared interfaces will be used as a functional interface, 1.8 add annotations
• Annotations in other annotations, known as meta annotations (meta Annotation)
◦ @Retention indicate when the annotated annotation is to be used (that is, when the annotation is retained)
Just keep in source code, discard during compilation (retentionpolicy.runtime)
Annotations are saved to class files during compilation and are ignored when class files are loaded (Retentionpolicy.class)
Annotations are read when the class file is loaded, which means that annotations are available in the runtime, and can be obtained by reflection (Retentionpolicy.runtime)
◦ @Documented indicate that annotations will be written to the Javadoc document when you generate Javadoc
◦ @Target indicate the scope of the annotation being annotated
Elementtype.type: Used to describe classes, interfaces (including annotation types) or enum declarations
Elementtype.field: Used to describe domains
Elementtype.method: Used to describe methods
Elementtype.parameter: Used to describe parameters
Elementtype.constructor: Used to describe constructors
Elementtype.local_variable: Used to describe local variables
Elementtype.annotation_type: Used to describe annotations
Elementtype.package: Used to describe packages
◦ @Inherited indicate that the annotation being annotated is inherited, that is, if a @inherited-decorated annotation type is used for a class, then the annotation is also used as a subclass of the modified class.
◦ @Repeatable indicate that annotated annotations can be used multiple times for the same object, 1.9 new annotations
Custom annotations
It says so many annotations, we focus on meta annotations, we usually use meta annotations to help us when we customize annotations. The custom annotation format is public @interface Note name {definition body}, and the Java.lang.annotation.Annotation interface is automatically inherited when you use @interface to customize annotations. When you customize annotations, you cannot inherit other annotations or interfaces. The method declared in the note actually declares a note parameter, the name of the method is the name of the parameter, and the return value type is the type of the parameter, which can be declared by default.
Custom annotations are simple, using @interface to define an annotation, as follows.
@Retention (retentionpolicy.runtime)
@Target (elementtype.type)
@Documented public
@interface ClassInfo {
String author () default "Wang";
String date ();
String comments ();
}
A custom annotation named ClassInfo, according to @retention can be known that the annotation will always exist, that is, when the program is running, this annotation is still valid; @Target (Elementtype.type) Indicates that the ClassInfo annotation is a function of a class, interface, or enum declaration; @Documented
Description ClassInfo information can be written to the Javadoc document.
Take a look at some of the annotation parameters in the custom note, which has three annotation parameters, which can set default values, such as author annotation parameters, the default value is Wang, and the other two parameters have no default value.
Let's look at another custom annotation.
@Retention (retentionpolicy.runtime)
@Target (elementtype.method) public
@interface MethodInfo {
String Description () Default "No description";
String date ();
}
This custom annotation MethodInfo is a function of the method, and the annotation will exist when the program is running; there are two annotation parameters in it.
The definition of the annotation parameter (the definition of the method) can be used only with public or default two access modifiers, and the type of the parameter supports the following.
• Eight basic types of data (Byte,int,short,long,float,double,char,boolean)
String Type
class type
enum type
annotation Type
• All types of arrays above
Use of annotations
In addition to the two annotations above, a field-scoped annotation is added.
@Retention (retentionpolicy.runtime)
@Target (elementtype.field) public
@interface FieldInfo {
String Type ();
String name ();
}
Note Parameters in custom annotations If you do not declare a default value, you must assign values to these parameters when using custom annotations, or the compiler will complain.
Take a look at the code that the annotation uses:
@ClassInfo (author = "Wang",
date = "2016/9/13",
comments = "Annotation demo") Public
class Annotationdemo { c4/> @FieldInfo (type = ' public ', name = ' Firstfield ') public
int Firstfield;
@FieldInfo (type = "Private", name = "Secondfield")
private String Secondfield;
@MethodInfo (Description = "method in Annotationdemo", name = "FirstMethod") public
void FirstMethod (String value) {
system.out.printf ("involved");
@MethodInfo (Description = "method in Annotationdemo", name= "Secondmethod")
private void Secondmethod () {
System.out.printf ("involved");
}
Get note information
To get the annotation information, you first have to ensure that the annotation exists in the program runtime, so you will normally add a @retention (retentionpolicy.runtime) annotation to the custom annotation, so that in the process of running the program, we can get some annotation information through reflection. For a description of reflection, you can view this article.
public class Annotationtest {public static void main (string[] args) {Resolveclassannotationinfo (annotationdemo.class
);
Resolvefieldannotationinfo (Annotationdemo.class);
Resolvemethodannotationinfo (Annotationdemo.class); } private static void Resolveclassannotationinfo (Class<?> clz) {//Determine if the class has ClassInfo annotations if (clz.isannotationpres
ENT (Classinfo.class)) {ClassInfo ClassInfo = (ClassInfo) clz.getannotation (Classinfo.class);
System.out.println (Classinfo.author () + "" + classinfo.comments () + "" + classinfo.date ());
} private static void Resolvefieldannotationinfo (Class<?> clz) {field[] fields = Clz.getdeclaredfields (); for (Field field:fields) {if (Field.isannotationpresent (Fieldinfo.class)) {FieldInfo FieldInfo = (FieldInfo) fi
Eld.getannotation (Fieldinfo.class);
System.out.println (Fieldinfo.type () + "" + fieldinfo.name ()); }} private static void Resolvemethodannotationinfo (Class<?> clz) {method[] methods =Clz.getdeclaredmethods (); For (method Method:methods) {if (Method.isannotationpresent (Methodinfo.class)) {MethodInfo MethodInfo = (methodi
NFO) method.getannotation (Methodinfo.class);
System.out.println (Methodinfo.name () + "" + methodinfo.description ());
}
}
}
}
Through the reflection to get the Field/method in the class and so on, through the getannotation () or getannotations () to get the relevant annotations, get the specific annotation can get concrete information.
The output of the run results is as follows:
Figure-1 Run result chart
Summarize
For beginners in Java, even Java developers who have some experience, there may be less contact with Java annotations, and in practice, annotations are rarely used, but they are often seen in the code, which is a straightforward introduction to annotations, at least at the code level, with no pressure to read.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.