SoFunction
Updated on 2025-03-06

Java Annotation Study Notes

Notes

Java annotations, also known as Java annotations, are special syntax metadata that has been supported by the Java language version 5.0 to add source code. This provides a formal way for us to add information to our code, allowing us to use this data very conveniently at some later point. Classes, methods, variables, parameters, and packages in the Java language can all be marked. Unlike Javadoc, Java annotations can obtain annotated content through reflection. When the compiler generates the class file, the annotations can be embedded in the bytecode. The Java virtual machine can retain the annotation content and can obtain the annotation content at runtime.

Built-in annotation

Java defines a set of annotations, with 7 in total, 3 in the middle, and 4 in the middle.

1. The annotation used in the code is:

  • @Override - Check if the method is a rewrite method. If it is found that the parent class or the referenced interface does not have this method, a compilation error will be reported.
  • @Deprecated - Tag outdated method. If this method is used, a compilation warning will be reported.
  • @SuppressWarnings - Instructs the compiler to ignore warnings declared in the annotation.

2. The annotations (or meta annotations) that act on other annotations are:

  • @Retention - Identifies how to save this annotation, whether it is only in the code, or is compiled into a class file, or can be accessed through reflection at runtime.
  • @Documented - Tags whether these annotations are included in the user documentation.
  • @Target - Tag what kind of Java member this annotation should be.
  • @Inherited - mark which annotation class this annotation inherits from (the default annotation does not inherit from any subclass)

3. Starting from Java 7, 3 additional annotations have been added:

  • @SafeVarargs - Java 7 starts supporting, ignoring any warnings generated by methods or constructor calls that use arguments as generic variables.
  • @FunctionalInterface - Java 8 starts to support, identifying an anonymous function or functional interface.
  • @Repeatable - Java 8 has started to support it, identifying that a certain annotation can be used multiple times on the same declaration.

Meta Note

Meta-annotations are the annotations mentioned above that are used on other annotations.

1.@Retention: Indicates the life cycle of this annotation

Life cycle type describe
Tagged comments are only kept at the source level and are ignored by the compiler.
Tagged comments are retained by the compiler at compile time, but are ignored by the Java virtual machine (JVM).
Tagged annotations are reserved by the JVM, so the runtime environment can use it.

2.@Documented: Indicates that the elements of this annotation can be documented by Javadoc or similar tools.

3.@Target: Indicates that the java element type that this annotation can apply

Target type describe
Can be applied to any element of a class.
Can be applied to fields or attributes.
Can be applied to method-level annotations.
Can be applied to the parameters of the method.
Can be applied to constructors.
ElementType.LOCAL_VARIABLE Can be applied to local variables.
ElementType.ANNOTATION_TYPE Can be applied to comment types.
Can be applied to package declarations.
ElementType.TYPE_PARAMETER New version 1.8, applied to type variables
ElementType.TYPE_USE New version 1.8, applied to any statement using type (such as types in declaration statements, generics, and cast statements)

4.@Inherited: indicates that the annotation of the @Inherited annotation is used, and the subclass of the marked class will also have this annotation.

5.@Repeatable: introduced in Java SE 8, the @Repeatable annotation indicates that the tagged annotation can be used multiple times to the same declaration or type (that is, it can be used repeatedly on the same class, method, attribute, etc.).

Custom annotations

In fact, after saying so much, they are all summative knowledge points. I dare to say that until now, everyone is still confused about the annotations. If you want to better understand annotations, you can only define annotations ourselves to implement one of our annotations and become familiar with the workflow of the annotations by implementing one of our own annotations.

Custom annotations in Java are similar to creating an interface. Declaring annotations requires the following things:

  • Modifier: The access modifier must be public, and the default is public if not written;
  • Keyword: The keyword is @interface;
  • Annotation name: The annotation name is the name of a custom annotation, and it will also be used when using it;
  • Annotation type element: Annotation type element is the content of the annotation and can be understood as the implementation part of the custom interface.

At the same time, the following things need to be paid attention to:

  • The annotation method cannot have parameters;
  • The return type of annotation method is limited to primitive types, strings, enums, annotations, or arrays composed of the above types;
  • Annotation methods can contain default values;
  • Annotations can contain meta annotations bound to them, and meta annotations provide information for the annotations.

Now that the rules are known, I will encode and implement a custom annotation. For example, when we implement a custom ORM framework, we will use annotations to realize the mapping between the data table name and the JAVA class, and the mapping relationship between the table fields and the JAVA class fields. Let’s simply implement this function.

Define Table annotation:

package ;

import ;
import ;
import ;
import ;

@Target(value={})
@Retention()
public @interface Table {
   String value();
}

Definition field annotation:

package ;

import ;
import ;
import ;
import ;

@Target(value={})
@Retention()
public @interface FieldMapping {
   String name();
   String type();
   int length();
}

Application Note:

package ;

import ;
import ;

@Table("tb_student")
public class Student {
   @FieldMapping(name = "id", type = "int", length = 10)
   private int id;

   @FieldMapping(name = "name", type = "varchar", length = 6)
   private String stuName;

   @FieldMapping(name = "age", type="int", length = 4)
   private String stuAge;

   // Omit getter and setter}

Read annotation information:

package ;

import ;
import ;

import ;

public class Main {

   public static void main(String[] args) {
       try {
           Class clazz = ("");

           // Annotations on the query class           Table tbStudent = (Table)();
           (());

           // Query the annotation on the attribute           Field stuId = ("id");
           FieldMapping fieldStuId = ();
           (() + "--" + () + "--" + ());

           Field stuName = ("stuName");
           FieldMapping fieldStuName =
                   ();
           (() + "--" + () + "--" + ());

           Field stuAge = ("stuAge");
           FieldMapping fieldStuAge =
                   ();
           (() + "--" + () + "--" + ());

           //Splicing the data found above into SQL statement           String name = "jelly";
           String sql =
                   "select * from " + () + " where " + () + " = '" + name + "'";
           ("SQL=" + sql);
      } catch (Exception e) {
           // Handle the exception
      }
  }
}

Through the above code, do you feel that custom annotations are still very simple; at the same time, do you feel that the function of annotations is very powerful?

Summarize

In general, the function of annotation is very powerful, but it is indeed very simple to use. This is the characteristic of awesome things, which are easy to use and do not feel complicated. When you encounter annotated things in the future, you will no longer be scared or confused.

The above is the detailed content of Java annotation study notes. For more information about Java annotation, please follow my other related articles!