English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Annotation Annotation Analysis

Overview

       Java in1.5The annotation Annotation is introduced in version, also known as Java annotation. Annotations are a kind of syntax metadata that can be directly used in the source code, class/Methods/Variables/Parameters/Package names and others can be annotated. Unlike Javadoc tags, the compiler can retain the annotation code when generating the class file, and possibly to retain the annotations during the program's execution (run-Annotations can be used in the time() method. The Java virtual machine will retain the annotations, allowing the reflection to obtain the relevant information of the AnnotationAnnotation.

Built-in annotations

In fact, we often encounter annotations in our daily lives, such as @Override, @Deprecated, etc., these are built-in annotations in JDK, let's take a look at the main built-in annotations of Java first.
 •Annotations that act on Java code
◦@Override checks whether a method is an overridden method, and if this method is not found in the superclass or implemented interface, the compilation will fail.
 ◦@Deprecated marks a method or class as deprecated, and a warning will be reported during the compilation process if the class or method is used
 ◦@SuppressWarnings notifies the compiler to ignore warnings about the parameters marked
 ◦@SafeVarargs ignores warnings about calling methods or constructors with generic parameters1.7New annotation
 ◦@FunctionalInterface indicates that a declared interface will be used as a functional interface1.8New annotation

•Annotations that are annotations of other annotations are called meta-annotations (Meta Annotation)
◦@Retention indicates when the annotation marked is used (that is, when the annotation will be retained)
■Only retained in the source code, discarded during the compilation process (RetentionPolicy.RUNTIME)
 ■Annotations are saved to the class file during the compilation process and ignored when the class file is loaded (RetentionPolicy.CLASS)
 ■Annotations are read when the class file is loaded, that is, annotations are available during runtime, and annotation information can be obtained through reflection (RetentionPolicy.RUNTIME)

 ◦@Documented indicates that the annotation marked will be written into the Javadoc document when generating Javadoc
 ◦@Target indicates the scope of the annotation marked
■ElementType.TYPE: Used to describe a class, interface (including annotation types) or enum declaration
 ■ElementType.FIELD: Used to describe a field
 ■ElementType.METHOD: Used to describe a method
 ■ElementType.PARAMETER: Used to describe a parameter
 ■ElementType.CONSTRUCTOR: Used to describe a constructor
 ■ElementType.LOCAL_VARIABLE: Used to describe a local variable
 ■ElementType.ANNOTATION_TYPE: Used to describe an annotation
 ■ElementType.PACKAGE: Used to describe a package

 ◦@Inherited indicates that the annotation marked is inherited, which means that if an annotation type decorated with @Inherited is used in a class, then this annotation will also take effect on the subclass of this class.
 ◦@Repeatable indicates that the annotated annotation can be applied multiple times to the same object,1.9New annotation

 Custom annotation

As mentioned above, many annotations have been discussed. Everyone should focus on meta-annotations, as we often use meta-annotations to assist us when defining custom annotations. The format of a custom annotation is public @interface annotationName {body}, and when using @interface to define a custom annotation, it automatically inherits the java.lang.annotation.Annotation interface. When defining a custom annotation, you cannot inherit other annotations or interfaces. The methods declared in the annotation are actually declaring an annotation parameter, where the method name is the name of the parameter, and the return type is the type of the parameter. The default keyword can be used to declare the default value of the parameter.

Defining a custom annotation is very 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 is defined, according to @Retention, we can know that this annotation will always exist, that is, it is still valid during the program's runtime; @Target(ElementType.TYPE) indicates that the ClassInfo annotation is used for class, interface, or enum declarations; @Documented
It explains that ClassInfo information can be written into the Javadoc document.

Let's take a look at some annotation parameters in the custom annotation, which contains three annotation parameters. Annotation parameters can be set with default values, for example, the author annotation parameter has a default value of Wang, while the other two parameters do not have default values.

Let's take a 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 used for methods, and it also exists during the program's runtime; it contains two annotation parameters.

The definition of annotation parameters (method definition) can only use the public or default access modifiers, and the parameter types support the following several types.
 •Eight basic data types (byte, int, short, long, float, double, char, boolean);
 •String type
 •Class type
 •enum type
 •Annotation type
 •All types of arrays

Annotation usage

In addition to the two annotations mentioned above, another Field scope annotation has been added.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldInfo {
 String type();
 String name();
}

If the annotation parameters in the custom annotations are not declared with default values, these parameters must be assigned when using the custom annotations; otherwise, the compiler will report an error.

Let's look at the code for using annotations:

@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");
 }
}

Obtain annotation information

To obtain annotation information, it is first necessary to ensure that the annotation exists during program execution. Therefore, it is generally added with the meta-annotation @Retention(RetentionPolicy.RUNTIME) to the custom annotation, so that during the program execution process, we can obtain some annotation information through reflection. For more information about reflection, you can refer to 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 a 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());
   }
  }
 }
}

Obtaining Field in Class through Reflection/Method, etc., through getAnnotation() or getAnnotations() to obtain related annotations, and obtain specific annotations to obtain specific information.

The running result output is as follows:


Figure-1 Running Result Diagram

Summary

For beginners in Java or even Java developers with some experience, the contact with Java annotations may be relatively less, and in practice, annotations are rarely used, but they are often seen in the code. This article is a brief introduction to annotations, at least it is pressure-free to read at the code level.

That's all for this article, I hope it will be helpful to everyone's study, and I also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo manual editing, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When sending an email, please replace # with @ to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like