Overview
Java introduced annotation in version 1.5, also known as Java annotation. Annotation is a kind of syntax metadata that can be used directly in the source code, and classes/methods/variables/parameters/package names, etc. can be annotated. Unlike Javadoc tags, the compiler can retain the annotation code when generating the class file. At the same time, in order to use annotations during the run-time process, the Java virtual machine keeps the annotation, so that the relevant information about the annotation can be obtained through reflection.
Built-in annotations
In fact, we often encounter annotations, such as @Override, @Deprecated, etc. These are all built-in annotations in JDK. Let’s first take a look at what are the main built-in annotations in Java.
•Annotations that act on Java code
◦@Override Checks whether a method is a rewrite method. If this method is not found in the parent class or the implemented interface, a compilation error will occur.
◦@Deprecated marks that a method or class is discarded. If the class or method is used, the compilation process will alert you.
◦@SuppressWarnings Notify the compiler to ignore warnings about the annotated parameters
◦@SafeVarargs Ignore warnings about calling methods or constructors containing generic parameters, 1.7 has added annotations
◦@FunctionalInterface indicates that a declared interface will be used as a functional interface. 1.8 has added annotation
•Annotations made on other annotations are called meta annotations (Meta Annotation)
◦@Retention Specifies when the annotated annotation is used (that is, when the annotation will be retained)
■Retention in source code only and discarded during compilation (RetentionPolicy.RUNTIME)
■Annotations are saved to the class file during compilation, and are ignored when the class file is loaded (RetentionPolicy.CLASS)
■Annotations are read when the class file is loaded, that is, annotations are available during operation. Annotations can be obtained through reflection (RetentionPolicy.RUNTIME)
◦@Documented Indicates that when generating Javadoc, the annotated annotations will be written to the Javadoc document.
◦@Target Specifies the scope of the annotated annotation■ElementType.TYPE: used to describe a class, interface (including annotation type) or enum declaration■ElementType.FIELD: used to describe the domain■ElementType.METHOD: used to describe the method■ElementType.PARAMETER: used to describe the parameters■ElementType.CONSTRUCTOR: used to describe the constructor■ElementType.LOCAL_VARIABLE: used to describe the local variable■ElementType.ANNOTATION_TYPE: used to describe the annotation■ElementType.PACKAGE: used to describe the package
◦@Inherited indicates that the annotation is inherited, that is, if an annotation type modified by @Inherited is used for a class, the annotation will also act on the subclass of the modified class.
◦@Repeatable indicates that the annotated annotation can be applied to the same object multiple times. 1.9 has added annotation
Custom annotations
I have mentioned so many annotations above, and everyone focuses on meta annotations. When we customize the annotations, we usually use meta annotations to assist us. The custom annotation format is public @interface annotation name { definition body }. When using @interface custom annotation, the java.lang.annotation.Annotation interface is automatically inherited. When customizing annotations, other annotations or interfaces cannot be inherited. The method declared in annotation is actually a comment 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 can be declared through default.
Custom annotations are simple, use @interface to define an annotation, as follows.
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documentedpublic @interface ClassInfo { String author() default "Wang"; String date(); String comments();} A custom annotation called ClassInfo. According to @Retention, you can know that this annotation will always exist, that is, this annotation is still valid when the program is running; @Target(ElementType.TYPE) means that ClassInfo annotation acts on the class, interface or enum declaration; @Documented
Instructions ClassInfo information can be written into Javadoc documents.
Let’s take a look at some annotation parameters in custom annotations. There are three annotation parameters. The annotation parameters can be set by default, such as the author annotation parameter, the default value is Wang, and the other two parameters have no default values.
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 acts on the method, and this annotation will also exist when the program is running; there are two annotation parameters in it.
To annotate the definition of parameters (method definition), you can only use two access rights modifiers public or default. The parameters types support the following types.
•Eight basic data types (byte, int, short, long, float, double, char, boolean)
•String type
•Class type
•enum type
•Annotation type
•Arrays of all types above
Use of annotations
In addition to the above two annotations, an annotation with Field scope has been added.
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface FieldInfo { String type(); String name();}If the default values are not declared in custom annotations, these parameters must be assigned values when using custom annotations, otherwise the compiler will report an error.
Take a look at the code used by the annotation:
@ClassInfo(author = "wang", date = "2016/9/13", comments = "annotation demo")public class AnnotationDemo { @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("first method involved"); } @MethodInfo(description = "method in AnnotationDemo", name="secondMethod") private void secondMethod() { System.out.printf("first method involved"); }}Get annotation information
To obtain annotation information, we must first ensure that the annotation will exist during the program run. Therefore, we generally add @Retention(RetentionPolicy.RUNTIME) meta annotation to custom annotations. In this way, during the program run, we can obtain some annotation information through reflection. For instructions on 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 whether this class has ClassInfo annotation if(clz.isAnnotationPresent(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) field.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 = (MethodInfo) method.getAnnotation(MethodInfo.class); System.out.println(methodInfo.name() + " " + methodInfo.description()); } } }}Reflection to obtain Field/Method in the class, etc., and obtain relevant annotations through getAnnotation() or getAnnotations(). You can obtain specific information by getting the specific annotations.
The output of the run result is as follows:
Figure-1 Operation result diagram
Summarize
For beginners of Java and even Java developers with certain experience, they may have less exposure to Java annotations. In reality, annotations are rarely used, but they will often see them in the code. This article is a simple introduction to annotations, and at least at the code level, it is stress-free to read.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.