Java Learning Route (24) - Notes

1. Overview
(1) Overview of Notes

  • Java annotation (Annotation), also known as Java annotation, is an annotation mechanism introduced by JDK5.
  • Classes, constructors, methods, member variables, parameters, etc. in the Java language can be annotated in the form of annotations.

(2) The role of annotations

  • Mark the classes, methods, and variables in Java, and then perform special processing.

2. Custom annotation
(1) Custom annotation format

public @interface 注解名称 {
	public 属性类型 属性名() default 默认值;
}

(2) Example of custom annotation

public @interface MyBook {
    
    
    String id();
    String[] names();
    double price();
    //特殊的属性value,当只定义一个属性且名称为value则调用时可不写value,若有多个,则必须填写
    String value();
}


3. Meta annotations

(1) Concept: meta-annotation is a form of annotation that acts on annotations in the form of annotations.

(2) Common meta annotations

  • @Target - restrict the scope of use of custom annotations
  • @Retention - declares the life cycle of annotations

(3) Common values ​​of common meta-annotation parameters

@Target - ElementType enumeration class

value scope
TYPE class/interface
FIELD Member variables
METHOD member method
PARAMETER method parameters
CONSTRUCTOR constructor
LOCAL_VARIABLE local variable

@Retention - RententionPolicy enumeration class

value scope
SOURCE Acting on the source code stage, the generated bytecode file does not exist
CLASS Acts on the source code stage, the bytecode file stage, does not exist in the runtime stage, the default value
RUNTIME Acting on the source code stage, bytecode file stage, running stage, commonly used in development

(4) Using meta annotations

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Book{
    
    
    String value();
}

Four, annotation analysis

(1) Concept: Annotation parsing is to determine whether an annotation exists and analyze its content.

(2) Related APIs

  • Annotation interface: the original interface of the annotation
  • AnnotationElement: defines the annotation parsing method
method illustrate
Annotation[] getDeclaredAnnotations() Get all annotations used on the current object and return an array of annotations
T getDeclaredAnnotation(Class<T> annotationClass) Obtain the corresponding annotation object according to the annotation type
boolean isAnnotationPresent(Class<Annotation> annotationClass) Determine whether the object uses the specified interface

(3) Skills for parsing annotations: Which component is the annotation on, which component object should be parsed first

(4) Case Analysis

@Target({
    
    ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Book{
    
    
    String value(); //书名
    double price() default 100; //价格 默认为100
    String[] authors(); //多位作者
}

@Book(value = "《Java深度学习》",price = 100,authors = {
    
    "xxx","xxx","xxx"})
class BookStore{
    
    
    private String name;
    private double price;
    private String[] authors;

    @Book(value = "《Java浅度学习》",price = 50,authors = {
    
    "佚名"})
    public void text(){
    
    

    }

    @Override
    public String toString() {
    
    
        return "BookStore{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", authors=" + Arrays.toString(authors) +
                '}';
    }
}


public class AnnotationDemo{
    
    
    @Test
    public void parseClass(){
    
    
        //1、先得到类对象
        Class c = BookStore.class;

        //2、判断是否存在
        if (c.isAnnotationPresent(Book.class)){
    
    
            //3、直接获取注解对象
            Book annotation = (Book) c.getDeclaredAnnotation(Book.class);
            System.out.println(annotation.value());
            System.out.println(annotation.price());
            System.out.println(Arrays.toString(annotation.authors()));
        }
    }

    @Test
    public void parseMethod() throws NoSuchMethodException {
    
    
        //1、先得到类对象
        Method c = BookStore.class.getMethod("text");
        //2、判断是否存在
        if (c.isAnnotationPresent(Book.class)){
    
    
            //3、直接获取注解对象
            Book annotation = (Book) c.getDeclaredAnnotation(Book.class);
            System.out.println(annotation.value());
            System.out.println(annotation.price());
            System.out.println(Arrays.toString(annotation.authors()));
        }
    }
}

/*测试结果*/Java深度学习》
100.0
[xxx, xxx, xxx]
======================Java浅度学习》
50.0
[佚名]

5. The application of annotations - simulating the Junit test framework

/*
* 需求:定义若干个方法,只要加了MyTest注解,就可以触发执行
* 分析:获取类中成员方法,判断是否有注解,若有注解则执行,否则不执行
*/

public class JunitDemo {
    
    

    @MyJunit
    public static void test1(){
    
    
        System.out.println("=======test1========");
    }

    public static void test2(){
    
    
        System.out.println("=======test2========");
    }


    @MyJunit
    public static void test3(){
    
    
        System.out.println("=======test3========");
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
    
    
        Class anno = JunitDemo.class;
        Method[] methods = anno.getMethods();

        for (Method method :methods) {
    
    
            if (method.isAnnotationPresent(MyJunit.class)){
    
    
                method.invoke(anno);
            }else System.out.println(method.getName() + "未执行");
        }
    }

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyJunit{
    
    }

Guess you like

Origin blog.csdn.net/Zain_horse/article/details/131094226