In Java, annotations were introduced in Java5 to describe meta information about Java code. Annotations generally do not directly affect code execution, although some annotations can be used to do so.

What can annotations do

Annotations in Java typically play the following roles

  • Compiler instruction
  • Build-time instruction
  • Runtime instruction

Among them

  • Java comes with three built-in compiler instructions, which are highlighted later in this article
  • Java annotations can be applied at build time, when you are building your project. The build process includes generating source code, compiling source code, generating XML files, packaging compiled source code and files into JAR packages, etc. Software builds are often automated using tools such as Apache Ant and Maven. These build tools scan Java code for specific annotations and generate source code or files based on those annotations.
  • Normally, annotations don’t appear in compiled code, but they can if you want to. Java supports runtime annotations, which can be accessed using Java reflection. The purpose of runtime annotations is usually to provide instructions to programs and third-party apis.

Annotations based

A simple Java annotation similar to @Entity. Where @ means to tell the compiler that this is an annotation. Entity is the name of the annotation. Usually in a document, it’s written like this

public @interface Entity  {  }

Annotation element

Java annotations can set some values using elements, which are similar to attributes or parameters. Defines sample code for annotations that contain elements

public @interface Entity  { String tableName (); }

Sample code using annotations containing elements

  @Entity ( tableName = "vehicles" )

The element name for the above annotation is tableName and the value is set to vehicles. Annotations with no elements need not use parentheses.

If the annotation contains more than one element, use the following method

@Entity ( tableName = "vehicles" ,  primaryKey = "id" )

If the annotation has only one element, we usually write it like this

@InsertNew ( value = "yes" )

But in this case, if and only if the element name is value, we can also abbreviate, that is, we don’t need to fill in the element name value, and the effect is as follows

  @InsertNew ( "yes" )

Annotations using

Annotations can be used to modify these elements in your code

  • class
  • interface
  • methods
  • The method parameters
  • attribute
  • A local variable

A complete use example is shown below

@Entitypublic class Vehicle { 
@Persistent protected 
StringvehicleName = null; 
@Getter public String getVehicleName(a) {
return this.vehicleName; 
} 

public void setVehicleName(@OptionalvehicleName) { 
this.vehicleName = vehicleName;
 } 
public ListaddVehicleNameToList(List names) {
 @Optional
   List localNames =names; 
     if(localNames == null) {
          localNames = new ArrayList(); 
     }

      localNames.add(getVehicleName());
      returnlocalNames; }}Copy the code

\


\

Built-in Java annotations

There are three built-in annotations in Java that provide instructions to the compiler. They are

  • @Deprecated
  • @Override
  • @SuppressWarnings

@Deprecated

  • Can be used to tag classes, methods, and properties.
  • If these three elements are no longer used, use the @deprecated annotation
  • The compiler warns if code uses a class, method, or attribute with the @deprecated annotation.

Deprecated is easy to use, as follows: annotate a Deprecated class.

@Deprecatedpublic class MyComponent {}
Copy the code

\

// When we use the Deprecated @deprecated annotation, it is recommended to use the corresponding @deprecated JavaDoc symbol and explain why the class, method, or property is Deprecated and what the alternative is.
@Deprecated
/ * *@deprecated This class is full of bugs. Use MyNewComponent instead.*/
public class MyComponent {}
Copy the code


\


\

@Override

The @Override annotation is used to modify a method that overrides a parent class. If this annotation is used by a method that is not overriding its parent class, the compiler prompts an error.

In fact, @overide is not required to override a parent class or interface method in a subclass. However, it is recommended to use this annotation. In some cases, if you change the name of the parent method, the previously overridden subclass method will no longer be overridden. Without @overide, you will not be aware of this subclass method. With this annotation modifier, the compiler prompts you for this information.

An example using the Override annotation

public class MySuperClass 
{ 
      public void doTheThing(a) {
              System.out.println("Do the thing"); }}public class MySubClassextends MySuperClass{ 
           @Override public void doTheThing(a) {
                  System.out.println("Do it differently"); }}Copy the code


\


\

@SuppressWarnings

  • @suppressWarnings Is used to suppress the compiler from generating warnings.
  • The elements that can be modified are classes, methods, method parameters, attributes, and local variables

Usage scenario: The compiler generates a warning when one of our methods calls a deprecated method or performs an unsafe type conversion. We can add the @SuppressWarnings annotation to this method to prevent the compiler from generating warnings.

Note: With the @SuppressWarnings annotation, use the proximity principle. If a method is warned, we try to use the @SuppressWarnings annotation for the method and not the class in which the method is annotated. Although both can inhibit the compiler from generating warnings, the smaller the range, the better, because the larger the range, we are not able to find warnings for other methods in this class.

Use the sample

@SuppressWarningspublic void methodWithWarning(a) {}
Copy the code


\

Create your own annotations

In Java, we can create our own annotations, which are defined in our own files, just like class and interface files. The following

@interface MyAnnotation { String value(a); String name(a); intage(); String[] newNames(); }Copy the code

\

The code above defines an annotation called MyAnnotation, which has four elements. Again, the @interface keyword is used to tell the Java compiler that this is an annotation.

If you look closely, you’ll see that the definition of an annotation element is very similar to the methods of an interface. These elements have types and names. These types can be

  • Primitive data type
  • String
  • Class
  • annotation
  • The enumeration
  • A one-dimensional array

The following is a custom annotation for applying

@MyAnnotation( value="123", name="Jakob", age=37, newNames={"Jenkov", "Peterson"})public class MyClass {}
Copy the code


\

Note that we need to set values for all the annotation elements, not one less.

Annotate element defaults

For an element in an annotation, we can set its default value as

@interface MyAnnotation { String value(a) default ""; Stringname(); int age(a); String[] newNames(); }Copy the code


\

In the code above, we set the default value of the value element to an empty string. When we use it, we can leave the value of value unset, that is, let value use the empty string default. Using sample code

“`java

@MyAnnotation( name=”Jakob”, age=37, newNames={“Jenkov”,”Peterson”})public class MyClass {}

@Retention is the annotation that decorates annotations. Using this annotation, we can * control whether annotations are written to the class file * control whether annotations in the class file are visible at runtime. Control is simple, using one of three strategies. * retentionPolicy. SOURCE indicates that annotations exist only in the SOURCE code, not in the.class file, and are not visible at runtime. Common annotations are @Override, @suppressWarnings. * retentionpolicy. CLASS this is the default annotation RetentionPolicy. Under this strategy, annotations will exist in the.class file, but will not be accessible by the runtime. Typically this annotation strategy is used for operations at some bytecode level. * RetentionPolicy.RUNTIME is accessible by the RUNTIME under this policy. Usually, we do things with reflection. Using the sample of the @ Retention ` ` ` Java import Java. Lang. The annotation. Retention; importjava.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interfaceMyAnnotation { String value() default ""; }Copy the code

\


\


\

@Target

Using the @Target annotation, we can specify which Java elements a custom annotation can modify. A simple example

\

import java.lang.annotation.ElementType;
importjava.lang.annotation.Target;
@Target({ElementType.METHOD})

public@interface MyAnnotation { 
String value(a);
}
Copy the code


\


\

The code above shows that the MyAnnotation annotation can only modify methods.

The @target parameter values are as follows

  • ElementType.ANNOTATION_TYPE
  • ElementType.CONSTRUCTOR
  • ElementType.FIELD
  • ElementType.LOCAL_VARIABLE
  • ElementType.METHOD
  • ElementType.PACKAGE
  • ElementType.PARAMETER
  • ElementType.TYPE (Note: any TYPE, i.e., the TYPE above, can be modified)

@Inherited

If you want a class and its subclasses to include an annotation, you use @Inherited to decorate the annotation.

java.lang.annotation.Inherited@Inheritedpublic @interfaceMyAnnotation {}

@MyAnnotationpublic class MySuperClass {... }public class MySubClass extends MySuperClass {... }Copy the code


\

The above code basically means

  1. Annotate MyAnnotation with the @Inherited annotation
  2. Annotate MySuperClass with MyAnnotation
  3. Implement a class MySubclass that inherits from MySuperClass

Through these steps, MySubClass also has MyAnnotation annotation.

These are some basic concepts about annotations in Java.