Deep understanding of Java: getting started with annotations and custom annotations
jieya 2021-06-04 10:15:21

In depth understanding of Java: annotation (Annotation) Getting started with custom annotations

Definition of annotations

Java Annotation is also called Java mark , yes JDK5.0 The version began to support adding special syntax metadata to the source code .
Java Class in language 、 Method 、 Variable 、 Parameters and packages can be labeled . and Javadoc Different ,Java Annotation can obtain annotation content through reflection . When the compiler generates class files , Annotations can be embedded in bytecode .Java The virtual machine can keep the annotation content , The annotation content can be obtained at runtime . Of course, it also supports customization Java mark .

Source location of meta annotation

Meta annotation analysis and examples

@Documented

Indicates that a type of comment will be passed by default javadoc And similar tools to record . This type should be used to annotate the type of annotation that affects the declaration of their customers using annotation elements . If a type declares an archived annotation , Annotation, which becomes the public part of the annotation element API Part of

import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Dog {
public String name() default "wangcai";
public int age() default 0;
}

@Inherited

This annotation is an identifying meta annotation , Indicates that the current annotation can be inherited by child annotations

import java.lang.annotation.Inherited;
@Inherited
public @interface testInherited {
Sring name();
}

@Target

For annotating classes 、 Interface ( Including annotation types ) or enum Statement , Separated by commas to indicate scope .

Key code

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
/** class 、 Declaration of interface or enumeration */
TYPE,
/** Field declaration (includes enum constants) */
/** Field declaration */
FIELD,
/** Method declaration */
/** Method declaration */
METHOD,
/** Formal parameter declaration */
/** Method formal parameter declaration */
PARAMETER,
/** Constructor declaration */
/** Declaration of construction method */
CONSTRUCTOR,
/** Local variable declaration */
/** Local local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
/** Parameter declarations *
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
/** Type used *
TYPE_USE
}

@Retention

Life cycle annotations , Indicates the length of time the annotation is kept , To what extent are the comments described valid

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
/** Comments will be discarded at compile time */
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
/** The compilation test is recorded in class In file , but VM Run time discard */
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
/** Runtime exists , It can be obtained by reflection */
RUNTIME
}

Custom annotation

Defining tags requires meta annotations

  • Use meta annotation @Target To mark the scope of the annotation ( The scope of space , Where can I use )
  • Use meta annotation @Retention To mark the time range of the annotation ( Time range , When it works )
  • Use meta annotation @Inherited To mark whether the annotation can be inherited by child annotations
  • Use meta annotation @Documented To mark whether the annotation needs to be automatically generated
  • Use @interface Keywords to define annotations
  • Define some related attributes inside the annotation , It's usually in the form of methods to define properties

Custom annotation instance

  • New custom annotation , Here we use idea For example , Where you want to create a new annotation , Right mouse button ->New->Java Class
  • Choose the way you want , Add name
    • choice Annotation, Create a new one Food The interface of
/**
* The annotation is a field annotation
* Description:
*
* @author: jieya
* Date: 2021-05-19
* Time: 18:05
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Food {
String name() default "";
}
  • choice Class, Create a new one
/**
* Here's the definition of food notes
* Description:
*
* @author: jieya
* Date: 2021-05-19
* Time: 18:11
*/
public class FoodAnnotation {
// Here is a separate definition
// @Target(ElementType.FIELD)
// @Retention(RetentionPolicy.RUNTIME)
// public @interface red {
// }
//
// @Target(ElementType.FIELD)
// @Retention(RetentionPolicy.RUNTIME)
// public @interface green {
// }
// Here we use the enumeration class definition
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface color {
/**
* Color enumeration
*
*/
public enum Color{RED,GREEN};
/**
* color property
*/
Color color() default color.Color.GREEN;
}
}
/**
* Defines an entity object class for food
* Description:
*
* @author: jieya
* Date: 2021-05-19
* Time: 18:34
*/
@Data
@AllArgsConstructor
public class FoodTest {
@Food
@FoodAnnotation.color(color = FoodAnnotation.color.Color.GREEN)
private String bread;
/**
* Drinks are not food , No comment
*/
private String drinks;
@Food
@FoodAnnotation.color(color = FoodAnnotation.color.Color.RED)
private String biscuits;
/**
* Here's how to use reflection to get annotations
*
* @param args
*/
public static void main(String[] args) {
// Define a food entity object
FoodTest food = new FoodTest(" Peach and plum bread ", " Hundred years ", " Darryland ");
// Get class template
Class c = food.getClass();
// Get all fields
for (Field f : c.getDeclaredFields()) {
// Determine whether the field has Food annotation
if (f.isAnnotationPresent(Food.class)) {
Food annotation = f.getAnnotation(Food.class);
System.out.println(" Field :[" + f.getName() + "]," + " This field uses Food annotation ");
// Determine whether the field has color annotation
if (f.isAnnotationPresent(FoodAnnotation.color.class)) {
FoodAnnotation.color.Color color = f.getAnnotation(FoodAnnotation.color.class).color();
System.out.println(" Field :[" + f.getName() + "]," + " This field uses color annotation " + " The color is " + color);
}
} else {
System.out.println(" Field :[" + f.getName() + "]," + " This field does not use annotations ");
}
}
}
}

FIELD Annotations are the most commonly used , The use of other annotation methods will not be repeated here , It's all the same .

Please bring the original link to reprint ,thank
Similar articles

2021-08-09

2021-08-09