Java basic tutorial on understanding Annotation

  • 2020-06-01 09:54:23
  • OfStack

Basic understanding of Java Annotation

1. The concept

Annontation is a new feature introduced by Java5. Chinese name 1 is called annotation. It provides a secure annotation-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on).

More colloquially, it means adding more intuitive and explicit instructions to the elements of the program (classes, methods, member variables) that are not related to the business logic of the program and are intended for use by the specified tool or framework.

Annontation is used in the declaration statements of packages, types, constructors, methods, member variables, parameters, and local variables, like a modifier 1.

Principle 2.

Annotation is actually an interface. Access annotation information via API related to Java's reflection mechanism. Related classes (classes in the framework or tools) use this information to decide how to use the program elements or change their behavior.

annotation will not affect the execution of the program code, no matter how annotation changes, the code will always execute as 1.

The Java language interpreter ignores these annotation at work, so in JVM these annotation "don't work" and can only be accessed and processed by supporting tools.

Similarities and differences between Annotation and interface:

1) the Annotation type USES the keyword @interface instead of interface.

This keyword statement implied a information: it is inherited java lang. annotation. Annotation interface, not declare a interface

2) the type and method definitions of Annotation are unique and limited.

Methods of type Annotation must be declared to have no arguments and no exceptions thrown. These methods define the members of annotation: the method name becomes the member name, and the method return value becomes the type of the member. The method return value type must be primitive, Class, enum, annotation, or a 1-dimensional array of elements with 1 of the preceding type as the element. The rest of the method can declare a member's default value using default and a default value. null cannot be used as a member default, which is quite different from the way we define methods in non-annotation types.

The Annotation type and its methods cannot take parameters of the annotation type, and the member cannot be generic. Only methods whose return value type is Class can use generic in annotation, because this method can convert various types to Class with class conversion.

3) the Annotation type is similar to the interface.

They can define constants, static member types (such as enumerated type definitions). The Annotation type can also be implemented or inherited as interface 1.

3. Application

As an auxiliary approach, annotation1 is usually used in software frameworks or tools, where different processes are taken according to different annontation annotations or the behavior of corresponding program elements (classes, methods, member variables, etc.) is changed.

For example, Junit, Struts, Spring and other popular tool frameworks are all widely used in annontion. Make your code more flexible.

4. Common standard Annotation

Starting with the java5 version, there are three standard annontation types,

(1) Override

java.lang.Override is a type marker annotation used as an annotation method. It shows that the annotated method overrides the parent method, acting as an assertion. If we use this annotation method when a parent method is not overridden, the java compiler will alert us with a compilation error.

This annotaton often adds a guaranteed check when we try to override the parent method and get the method name wrong.

(2) Deprecated

Deprecated is also a kind of marker annotation. When a type or type member is decorated with @Deprecated, the compiler will discourage the use of the annotated program element. So the use of this modification has a definite "continuity" : if we use the obsolete type or member in our code by inheritance or override, the compiler still alarms the inherited or overridden type or member even though it is not declared as @Deprecated.

Note: the @Deprecated annotation type is distinct from the @deprecated tag type in javadoc: the former is recognized by the java compiler, while the latter is recognized by the javadoc tool to generate documentation (including a description of why the program member is out of date and how it should be banned or replaced).

(3) SuppressWarnings

This annotation tells the Java compiler to turn off warnings for classes, methods, and member variables.

Sometimes a warning will be issued when compiling. Some of these warnings are hidden by Bug, and some are unavoidable. For some unwanted warnings, this annotation can be used to mask them.

SuppressWarning is not one marker annotation. It has one member of type String[], whose value is the forbidden warning name. For the javac compiler, the warning names that are valid for the -Xlint option are also valid for the @SuppressWarings option, and the compiler ignores the warning names that are not recognized.

The annotation syntax allows annotation names to be followed by parentheses, which are the comma-separated name=value pairs used to assign annotation members:

Code:


@SuppressWarnings(value={"unchecked","fallthrough"})

public void lintTrap() { /* sloppy method body omitted */ }

In this example, the SuppressWarnings annotation type only defines 1 single 1 member, so there is only 1 simple value={... } as name=value. Since the member value is an array, curly braces are used to declare the array value.

Note: we can abbreviate annotation in the following case: when annotation has only single 1 member, and the member is named "value=". You can go to "value=". For example, abbreviate SuppressWarnings annotation above:

Code:


@SuppressWarnings({"unchecked","fallthrough"})

If the number of prohibited warnings declared by SuppressWarnings is 1, you can leave out the curly braces:


@SuppressWarnings("unchecked")


5. Custom annontation example

The example involves four classes:

Listing 1: Author java


package com.magc.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

  /**
   *  Define the author information, name and group
   * @author magc
   *
   */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  @Documented
public @interface Author {

    String name();
    String group();
}

Listing 2: Description java


/**
 * 
 */
package com.magc.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author magc
 *
 *  Definition description information  value
 */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.TYPE)
  @Documented
  
public @interface Description {
    String value();
}

Listing 3: Utility java


package com.magc.annotation;

  @Description(value = " This is a 1 Useful utility classes ")
public class Utility {

    @Author(name = "haoran_202",group="com.magc")
    public String work()
    {
      return "work over!";
    }
    
    
  
}

Note: this is a normal Java class that runs the @Description and @Author annotations.

Listing 3: AnalysisAnnotation java


package com.magc.annotation;

import java.lang.reflect.Method;

public class AnalysisAnnotation {
  /**
   *  Analyze the processing at run time annotation Type of information 
   * 
   * 
   */
  public static void main(String[] args) {
    try {
        // Through runtime reflection API To obtain annotation information 
        Class rt_class = Class.forName("com.magc.annotation.Utility");
        Method[] methods = rt_class.getMethods();
        
        boolean flag = rt_class.isAnnotationPresent(Description.class);
        
        if(flag)
        {
          Description description = (Description)rt_class.getAnnotation(Description.class);
          System.out.println("Utility's Description--->"+description.value());
          for (Method method : methods) {
            if(method.isAnnotationPresent(Author.class))
            {
              Author author = (Author)method.getAnnotation(Author.class);
              System.out.println("Utility's Author--->"+author.name()+" from "+author.group());
              
            }
          }
        }
      
      
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
  }

}

Note: this is a basic framework or tool class that works with custom @Description and @Author to get information associated with the regular Java class Utility.java, i.e. description and author.

Run AnalysisAnnotation, and the output is:

Utility's Description--- > This is a useful utility class
Utility's Author--- > haoran_202 from com.magc

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: