COMMENTS - describe elements

Definition

Definition: Annotation, also known as metadata. A code level description. It is a feature introduced by JDK 1.5 and later. It is at the same level as class, interface and enumeration. It can be declared in front of package, class, field, method, local variable, method parameter, etc. to explain and comment these elements.
Concept description:
*New features after JDK 1.5
*Describing the procedure
*Use annotation: @ annotation name
Action classification:
① Document preparation: generate document (generate document doc document) through the annotation identified in the code
② Compile check: the compiler can realize basic compile check [Override] through the annotation identified in the code
③ Code analysis: analyze the code through the annotation identified in the code [use reflection]
Document: see link - >
Some predefined annotations in java are used for compilation checking, such as:
*Override: check whether the method marked by the annotation inherits from the parent class (Interface)
*@ Deprecated: the annotation indicates that it is out of date
*@ SuppressWarnings: suppress warnings. Generally, pass the parameter all, that is, @ SuppressWarnings("all")

@SuppressWarnings("all")//Make all warnings not pop up. Suppress the warnings
public class Demo01Annotation {
    @Override//Check whether the rewriting method specification is met
    public String toString() {
        return super.toString();
    }
    @Deprecated//Deprecated method
    public void show1(){
        //Defective
    }
    public void show2(){
        //Better way
    }
}

Custom annotation - for code analysis

1. How to customize annotation

 Custom annotation
		* format:
			Meta annotation
			public @interface annotation name{
				Attribute list;
			}

		*Essence: Annotation is essentially an interface, which inherits Annotation interface by default
			* public interface MyAnno extends java.lang.annotation.Annotation {}

		*Properties: abstract methods in interfaces
			* requirements:
				1. The return value type of the attribute has the following values
					*Basic data type
					* String
					* enumeration
					* notes
					*Array of the above types

				2. The attribute is defined, and it needs to be assigned a value when it is used
					1. If the default keyword is used to initialize the default value of a property when defining a property, the annotation can be used without assigning a value to the property.
					2. If only one attribute needs to be assigned and the name of the attribute is value, then value can be omitted and the value can be defined directly.
					3. When the array is assigned, the value is wrapped with {}. If there is only one value in the array, {} can be omitted

eg:

public @interface Demo02MyAnno {
    //Five kinds of return values
    int show1();
    int value()default 3;//If there is only one method and the name is value, value can be omitted
    String show2()default "Zhang San";
    Person show3();
    MyAnno2 show4();
    String[] show5();
}
@Demo02MyAnno(show1 =14,show2="abk",show3 =Person.P1,
				show4=@MyAnno2,show5={"aaa","bbb"})
public class Worker {
}

2. How to use meta annotation

 Meta annotation: annotation used to describe annotation
			*@ Target: describe where annotations can work
				*ElementType value:
					*TYPE: can act on a class
					*METHOD: can act on the METHOD
					*FIELD: can act on member variables
			*@ Retention: describes the stage when the annotation is retained
				*@ Retention(RetentionPolicy.RUNTIME): the currently described annotation will be kept in the class bytecode file and read by the JVM
			*@ Documented: describes whether annotations are extracted into api documents
			*Inherited: describes whether the annotation is inherited by the subclass

eg:

@Target(value = {ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnno3 {
}
@MyAnno3
public class Worker2 {
    @MyAnno3
    public final int A = 1;
    @MyAnno3
    public void method(){
    }
}

3. How to parse annotations (using reflection)

Using (parsing) annotations in a program: getting attribute values defined in annotations
		1. Get the object (Class, Method,Field) where the annotation is defined
		2. Get the specified comment
			* getAnnotation(Class)
			//In fact, a subclass implementation object of the annotation interface is generated in memory

		            public class ProImpl implements Pro{
		                public String className(){
		                    return "cn.itcast.annotation.Demo1";
		                }
		                public String methodName(){
		                    return "show";
		                }
		            }
		3. Call the abstract method in the annotation to obtain the configured property value

eg:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
    String className();
    String methodName();
}
//Parsing annotations using one of the methods
@Pro(className = "cn.java.Person",methodName = "eat")
public class Demo04 {
	public static void main(String[] args) throws Exception {
        //Get the bytecode file object of this class
        Class<Demo04> demo04Class = Demo04.class;
        //Get annotation object
        Pro annotation = demo04Class.getAnnotation(Pro.class);//Get the annotation Pro of demo04Class
        String className = annotation.className();//Get className
        String methodName = annotation.methodName();//Get methodName
        //Create reflected objects
        Class aClass = Class.forName(className);
        // Load into memory
        Object o = aClass.newInstance();
        //How to get objects
        Method method = aClass.getMethod(methodName);
        //Using object methods
        method.invoke(o);
    }
}

Customize the test framework with annotations

Tested classes:

public class Calculator {
    @Test
    public void add(){
        System.out.println("1 + 0 =" + (1 + 0));
    }
    @Test
    public void div(){
        System.out.println("1 / 0 =" + (1 / 0));
    }
}

Definition note:

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

}

Test method, generate bug.TXT file:

public class CheckTest {
    public static void main(String[] args) throws IOException {
        //1.
        Class<Calculator> c = Calculator.class;
        Calculator cal = new Calculator();
        //2.
        Method[] methods = c.getMethods();
        BufferedWriter bw = new BufferedWriter(new FileWriter("01_Junit\\src\\bug.txt"));
        int temp = 0;
        for (Method method : methods) {
            if(method.isAnnotationPresent(Test.class)){//isAnnotationPresent, annotated. class decoration returns true
                try{
                    method.invoke(cal);
                } catch (Exception e) {
                    temp++;
                    bw.write(method.getName()+"Method exception!");
                    bw.newLine();
                    bw.write("Name of exception:" + e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("Cause of abnormality:"+ e.getCause().getMessage());
                    bw.newLine();
                    bw.write("==============");
                    bw.newLine();
                }
            }
        }
        bw.write("In total"+ temp +"Secondary anomaly.");
        bw.flush();
        bw.close();

    }
}
76 original articles published, praised 0 and visited 564
Private letter follow

Tags: Attribute calculator Java JDK

Posted on Tue, 14 Jan 2020 20:27:52 -0800 by ErcFrtz