06 notes on learning

           Annotated learning notes

1 Introduction to notes

Note: use words to describe the program and show it to programmers

Note: it explains the program and shows it to the computer

Annotation, also known as metadata. A code level description. It is jdk1 A feature introduced in version 5 and later is at the same level as class, interface and enumeration.

It can be declared in front of packages, classes, fields, methods, local variables, method parameters, etc. to describe and annotate these elements.

​ . JDK1. New features after 5

​ . Description of the procedure

Function classification:

​ 1. Writing documents: generate documents through the annotations identified in the code [generate java doc documents]

​ 2. Code analysis: analyze the code through the annotation marked in the code [use reflection]

​ 3. Compilation check: enable the compiler to implement basic compilation check [override] through the annotations identified in the code

Annotation function:

Most of the time, annotations are used to replace the configuration file. Instead of configuring in the configuration file, annotations are directly assigned

2 generate doc documents for Java classes

1. Write Java classes

AnnotationDemo1.java

package com.tangguanlin.annotation;
/**
 * Note: annotation javadoc demo
 * Author: Tang Guanlin
 * Date: 14:00, January 2, 2022
 */
public class AnnotationDemo1 {
    /**
     * Calculate the sum of two numbers
     * @param a  integer
     * @param b  integer
     * @return Sum of two numbers
     */
    public int add(int a,int b ){
        return  a+b;
    }
}

2. Add annotationdemo1 Java is copied to the desktop folder annotation and encoded in ANSI format:

3. Open the command line and go to the annotation path,

Input: Javadoc annotationdemo1 Java enter

4. Open index with browser HTML, you can see the doc document of this class

3 JDK built-in annotation

3.1 @Override

@Override: check whether the method marked by the annotation inherits from the parent class (Interface)

package com.tangguanlin.annotation;
/**
 * Description: JDK built-in annotation
 * Author: Tang Guanlin
 * Date: 14:00, January 2, 2022
 */
public class AnnotationDemo2 {
    
    @Override  //@Override: check whether the annotated method inherits from the parent class
    public String toString() {
        return super.toString();
    }
}

3.2 @Deprecated

@Deprecated: the content marked by this annotation indicates that it is obsolete

@Deprecated //@The Deprecated annotation show1() method is obsolete and is not recommended
public void show1(){
    //Defective
}

Example:

Date date class is not recommended. Calendar date class is recommended:

3.3 @SuppressWarnings

@SuppressWarnings("all"): suppress warnings

@SuppressWarnings("all")
public class AnnotationDemo2 {
}

Example:

The show2() method has a warning message "Method show2() is never used"

After the annotation @ SuppressWarnings("all") is added, the warning disappears

Generally placed on class:

4 custom annotation

4.1 annotation format

Format:

public @interface Annotation name{};

Custom annotation @ MyAnnotation

package com.tangguanlin.annotation;
/**
 * Description: Custom annotation
 * Author: Tang Guanlin
 * Date: 15:00, January 2, 2022
 */
public @interface MyAnnotation {

}

Compile command:

javac MyAnnotation.java

Generate myannotation Class bytecode file

Decompile command:

javap MyAnnotation.class

The command line generates the original java code

public interface com.tangguanlin.annotation.MyAnnotation extends java.lang.annotation.Annotation {
    
}

The screenshot is as follows:

4.2 nature of notes

Annotation is essentially an interface, which inherits the annotation interface by default

public interface MyAnnotation extends Annotation {
    
}

4.3 annotation attributes

Properties: abstract methods that can be defined in an interface

1. Return value type of property:

Basic data type

​ String

Enumeration

Annotation

Arrays of the above types

package com.tangguanlin.annotation;
/**
 * Description: Custom annotation
 * Author: Tang Guanlin
 * Date: 15:00, January 2, 2022
 */
public @interface MyAnnotation {

    public abstract  String show1(); //Custom properties

}

Use notes:

@MyAnnotation(show1 = "1")
public void show2(){
	//Replace show1() method
}

Generally, the annotated attribute method is defined as the real attribute name: such as age

package com.tangguanlin.annotation;
/**
 * Description: Custom annotation
 * Author: Tang Guanlin
 * Date: 15:00, January 2, 2022
 */
public @interface MyAnnotation {

    public abstract  String age(); //Define the annotated attribute method as the real attribute name
    public String username();

}

Use, see the meaning of the name:

@MyAnnotation(age = "23",username = "zhangsan")  //Using annotations
public void show2(){
    //Replace show1() method
}

2. The attribute is defined, and it needs to be assigned a value when it is used

​ . If the default keyword is used to give the default initial value to the attribute when defining the attribute, the attribute can not be assigned when using annotation

​ . If only one attribute needs to be assigned and the name of the attribute is value, value can be omitted and the value can be defined directly

​ . When assigning an array value, the value is wrapped with {}. If there is only one value in the array, {} is omitted.

definition:

package com.tangguanlin.annotation;
/**
 * Description: Custom annotation
 * Author: Tang Guanlin
 * Date: 15:00, January 2, 2022
 */
public @interface MyAnnotation {

    public int value();
}

Use: for example: @ SuppressWarnings("all")

@MyAnnotation(2)  //The value attribute directly simplifies the writing of the value
public void show2(){
    //Replace show1() method
}

4.4 yuan notes

Meta annotation: an annotation used to describe an annotation

4.4.1 @Target

@Target: describes where annotations can work

ElementType.TYPE :   Indicates that MyAnnotation Annotations can only work on classes
ElementType.METHOD:  Indicates that MyAnnotation Annotations can only work on methods
ElementType.FIELD:   Indicates that MyAnnotation Annotations can only work on day-to-day variables

use:
@Target(value = ElementType.TYPE)
public @interface MyAnnotation2 {

}

definition:

package com.tangguanlin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
 * explain:
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@Target(value = ElementType.TYPE)  //Indicates that the MyAnnotation annotation can only act on classes
public @interface MyAnnotation2 {


}

4.4.2 @Retention

@Retention: describes the stage in which annotations are retained

RetentionPolicy.SOURCE :   Indicates that MyAnnotation Annotations can only work on code
RetentionPolicy.CLASS:   Indicates that MyAnnotation Annotations can only work on classes
RetentionPolicy.RUNTIME:   Indicates that MyAnnotation Annotations are retained until class Bytecode file and JVM Read
                                                 The annotations we define are generally taken RUNTIME value

use:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation2 {

}

definition:

package com.tangguanlin.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
 * explain:
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation2 {  //Indicates that the MyAnnotation annotation will be retained in the class bytecode file and read by the JVM


}

4.4.3 @Documented

@Documented: describes whether annotations are extracted into api documents

use:
@Documented
public @interface MyAnnotation2 {


}

Example:

definition:

package com.tangguanlin.annotation;
import java.lang.annotation.*;
/**
 * explain:
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
@Documented //Describes whether annotations are extracted into the api document
public @interface MyAnnotation2 {


}

use:

package com.tangguanlin.annotation;
import  com.tangguanlin.annotation.MyAnnotation;
/**
 * Description: JDK built-in annotation
 * Author: Tang Guanlin
 * Date: 14:00, January 2, 2022
 */
public class AnnotationDemo2 {

    @MyAnnotation2
    public void show2(){
        //Replace show1() method
    }
}

Generate java doc document:

4.4.4 @Inherited

@Inherited: describes whether annotations are inherited by subclasses

//use
@Inherited
public @interface MyAnnotation2 {


}

definition:

package com.tangguanlin.annotation;
import java.lang.annotation.*;
/**
 * explain:
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@Inherited  //Describes whether annotations are inherited by subclasses
public @interface MyAnnotation2 {


}

4.4.5 summary of meta notes

The commonly used meta notes are:

@ Target describes where annotations can work

@ Retention describes the stage in which annotations are retained

5 parsing notes

Parse annotation: get the attribute value defined in the annotation

​ 1. Gets the location object (Class, Method, Field) defined by the annotation

Class<ReflectTest> reflectTestClass = ReflectTest.class;

​ 2. Gets the specified annotation

ProAnnatation proAnnatation = reflectTestClass.getAnnotation(ProAnnatation.class);

In fact, a subclass implementation object of the annotation interface is generated in memory

public class ProAnnatationImpl implements Pro{

    public String classname(){
        return "com.tangguanlin.annotation.Student";
    }

    public String method(){
        return "sleep";
    }
}

​ 3. Call the abstract method in the annotation to get the configured property value

String className = proAnnatation.classname();

Case:

Requirements: the framework class writes a "framework". On the premise that any code of the class cannot be changed, it can help us create objects of any class and execute any method

realization:

Student.java

package com.tangguanlin.annotation;
/**
 * explain:
 * Author: Tang Guanlin
 * December 31, 2021
 */
public class Student {

    public void sleep(){
        System.out.println("sleep...");
    }
}

ProAnnatation.java annotation

package com.tangguanlin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Description: replace the configuration file with annotations
 *      Describe the class name and method name to be executed
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@Target(ElementType.TYPE) //Act on class
@Retention(RetentionPolicy.RUNTIME)
public @interface ProAnnatation {

    public String classname();

    public String method();
}

ReflectTest.java

package com.tangguanlin.annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * Description: the framework class writes a "framework". On the premise that any code of the class cannot be changed, it can help us create objects of any class and execute any methods
 * Author: Tang Guanlin
 * Date: 16:00, January 2, 2022
 */
@ProAnnatation(classname = "com.tangguanlin.annotation.Student",method = "sleep")
public class ReflectTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

         //1. Parsing notes
         //1.1 get the bytecode file object of this class
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        //1.2. Gets the annotation object above
              //In fact, a subclass implementation object of the annotation interface is generated in memory
                /*
                    public class ProAnnatationImpl implements Pro{

                        public String classname(){
                            return "com.tangguanlin.annotation.Student";
                        }

                        public String method(){
                            return "sleep";
                        }
                    }
                */
        ProAnnatation proAnnatation = reflectTestClass.getAnnotation(ProAnnatation.class);
         //1.3. Call the abstract method defined in the annotation object to obtain the return value
        String className = proAnnatation.classname();
        String methodName = proAnnatation.method();


        //3. Load this class into memory
        Class c1= Class.forName(className);
        //4. Create object
        Object object  = c1.newInstance();
        // 5. Get method object
        Method method = c1.getMethod(methodName);
        //6. Implementation method
        method.invoke(object);
    }
}

Operation results:

sleep...

6 annotated cases

6.1 requirements

Write a simple test framework,

After the main method is executed, all methods (Methods annotated with @ check) that will be automatically detected will judge whether there are exceptions in the method and record them in the file

6.2 code implementation

6.2.1 definition notes

Annotation class check Java: defining annotations

package com.tangguanlin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Description: define annotation @ Check
 * Author: Tang Guanlin
 * Date: 18:00, January 2, 2022
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}

6.2.2 use notes

Calculator class calculator Java: using annotations

package com.tangguanlin.annotation;
/**
 * Description: calculator class defined by Xiao Ming
 * Author: Tang Guanlin
 * Date: 18:00, January 2, 2022
 */
public class Calculator {

    //addition
    @Check
    public void add(){
        String str =null;
        str.toString();
        System.out.println("1+0="+(1+0));
    }

    //subtraction
    @Check
    public void sub(){
        System.out.println("1+0="+(1+0));
    }

    //multiplication
    @Check
    public void mul(){
        System.out.println("1*0="+(1*0));
    }

    //division
    @Check
    public void div(){
        System.out.println("1/0="+(1/0));
    }

    public void show(){
        System.out.println("Never bug...");
    }
}

6.2.3 analytical notes

TestCheck.java: parse annotations and use annotations to realize functions

package com.tangguanlin.annotation;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * Description: simple test framework
 *      After the main method is executed, all methods (Methods annotated with @ check) that will be automatically detected will judge whether there are exceptions in the method and record them in the file
 * Author: Tang Guanlin
 * Date: 18:00, January 2, 2022
 */
public class TestCheck {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, IOException {
          //1. Create calculator object
        Calculator calculator = new Calculator();
        //2. Get bytecode file object
        Class<Calculator> calculatorClass = Calculator.class;

        //3. Get all methods
        Method[] methods = calculatorClass.getMethods();

        int number = 0; //Number of exceptions
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));

        for(Method method:methods){
            //4. Is there @ check annotation on the method
            Check annotation = method.getAnnotation(Check.class);
            if(annotation!=null){
                //5. Implementation method
                try {
                    method.invoke(calculator);
                }catch (Exception e){
                    number++;
                    //6. Catch exceptions and record them to the file
                    bw.write(method.getName()+"The method is abnormal");
                    bw.newLine();
                    bw.write("Name of exception:"+e.getCause());
                    bw.newLine();
                    bw.write("Cause of abnormality:"+e.getCause().getMessage());
                    bw.newLine();
                    bw.write("-----------------------------");
                }
            }
        }
        bw.newLine();
        bw.write("A total of"+number+"Secondary anomaly");
        bw.flush();
        bw.close();
    }
}

Operation results:

bug.txt file content:

add The method is abnormal
 Name of exception: java.lang.NullPointerException
 Cause of abnormality: null
-----------------------------div The method is abnormal
 Name of exception: java.lang.ArithmeticException: / by zero
 Cause of abnormality:/ by zero
-----------------------------
There were 2 exceptions in this test

6.3 summary

​ 1. Most of the time in the future, we will use annotations instead of custom annotations

​ 2. For whom?

2.1 compiler

2.2 for the parser, for example: testcheck java

​ 3. Annotation is not a part of the program. It can be understood that annotation is a label

Keywords: Java

Added by Fazer on Tue, 04 Jan 2022 18:08:45 +0200