Java "Annotations" study notes

annotation:

  • Concept: description of the process. To the computer to see

  • Notes: The text description of the program. To the programmer to see

    • Definition: Notes Annotation( ), also known as metadata . Describe a code level. It is JDK1.5and a feature introduced in later versions, the classes, interfaces, enumerations are on the same level. It can be declared in front of the packages, classes, fields, methods, local variables, parameters and the like of the method for these elements will be described, the comment.

    • The concept Description:
      * JDK1.5New features after
      * description of the process of
      * using annotations: @ Name annotation

    • Role Category:
      ① documenting: by annotating generate a document [document generation doc documentation] code identified
      were the code by annotating code identification analysis [using reflection]: ② code analysis
      ③ compiler checks: notes by code identified so that the compiler can compile basic checking [Override]

package cn.itcast.annotation;

/**
 * 注解javadoc演示
 *
 * @author itcat
 * @version 1.0
 * @since 1.5
 */
public class AnnoDemo1 {

    /**
     * 计算两数的和
     * @param a 整数
     * @param b 整数
     * @return 两数的和
     */
    public int add(int a, int b ){
        return a + b;
    }
}

  • Some notes JDK predefined
    * @Override: detection method labeled the annotation whether inherited from the parent class (interface)
    * @Deprecated: the content of the annotation label indicating obsolete
    * @SuppressWarnings: compression warning
    * General passed parametersall ,@SuppressWarnings("all")
package cn.itcast.annotation;

import java.util.Date;

/**
 * JDK中预定义的一些注解
 * 		* @Override	:检测被该注解标注的方法是否是继承自父类(接口)的
 * 		* @Deprecated:该注解标注的内容,表示已过时
 * 		* @SuppressWarnings:压制警告
 *
 *
 */

@SuppressWarnings("all")
public class AnnoDemo2 {

    @Override
    public String toString() {
        return super.toString();
    }

    @Deprecated
    public void show1(){
        //有缺陷
    }

    public void show2(){
        //替代show1方法
    }

    public void demo(){
        show1();
        Date date = new Date();
    }
}
  • Custom annotation
    • Format:
      Yuan notes
public @interface 注解名称{
				属性列表;
			}
  • Essence: Notes essence on is a an interface , the interface inherits default Annotation Interface
public interface MyAnno extends java.lang.annotation.Annotation {}
  • Properties: abstract interface methods
    • Claim:
      1. Return Value Type attribute have the following values
        * basic data types
        * String
        * enumerated
        * Notes
        * an array of more than one type of
public @interface MyAnno {

     int value();
    Person per();
    MyAnno2 anno2();
    String[] strs();
     /*String name() default "张三";*/
     /*String show2();

     Person per();
     MyAnno2 anno2();

     String[] strs();*/
}

  1. The property is defined when you use need to give the property assignment
    1. If the definition of property, the use of defaultkeywords to attribute default initialization value, when using annotations, you can not assign attributes.
    2. If there is only a need to assign attribute, and value is the name of the property, the value may be omitted, directly defined value.
    3. array assignment, the value of the {} package. If the array has only one value, it can be omitted {}
  • Annotations are used to describe annotation: a meta-annotation
    • @Target: Annotation can describe the role of location
      • ElementTypeValue:
        • TYPE: It can act on the class
        • METHOD: It can act on the method
        • FIELD: It can act on the member variables
    • @Retention: Stage Description annotation reserved
      * @Retention(RetentionPolicy.RUNTIME): annotation currently being described, will be retained to the class bytecode files, and JVMread
    • @Documented: Whether the description of annotations are drawn to the api documentation
    • @Inherited: Description notes whether inherited by subclasses
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnno3 {
}
  • The program uses (Analysis) Note: getting a property value defined in the annotation
  1. Acquiring location defined annotation object (Class, Method, Field)
  2. Gets the specified comment
    getAnnotation(Class)
    // in fact generate a subclass that implements the interface annotation object in memory
   public class ProImpl implements Pro{
	                public String className(){
	                    return "cn.itcast.annotation.Demo1";
	                }
	                public String methodName(){
	                    return "show";
	                }
	            }
  1. Abstract method call annotation get property values ​​configured
package cn.itcast.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 描述需要执行的类名,和方法名
 */

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {

    String className();
    String methodName();
}




/**
 * 框架类
 */
@Pro(className = "cn.itcast.annotation.Demo1",methodName = "show")
public class ReflectTest {
    public static void main(String[] args) throws Exception {

        /*
            前提:不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
         */


        //1.解析注解
        //1.1获取该类的字节码文件对象
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        //2.获取上边的注解对象
        //其实就是在内存中生成了一个该注解接口的子类实现对象
        /*

            public class ProImpl implements Pro{
                public String className(){
                    return "cn.itcast.annotation.Demo1";
                }
                public String methodName(){
                    return "show";
                }

            }
 */

        Pro an = reflectTestClass.getAnnotation(Pro.class);
        //3.调用注解对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        System.out.println(className);
        System.out.println(methodName);





        //3.加载该类进内存
        Class cls = Class.forName(className);
        //4.创建对象
        Object obj = cls.newInstance();
        //5.获取方法对象
        Method method = cls.getMethod(methodName);
        //6.执行方法
        method.invoke(obj);
    }
}

  • Case: simple test framework
    • summary:
      1. After most of the time, we will use annotations, rather than custom annotation
      2. Who used to comment?
        1. translater
        2. Analytical procedures used to
      3. Annotations are not part of the program, notes that can be understood as a label
/**
 * 小明定义的计算器类
 */
public class Calculator {

    //加法
    @Check
    public void add(){
        String str = null;
        str.toString();
        System.out.println("1 + 0 =" + (1 + 0));
    }
    //减法
    @Check
    public void sub(){
        System.out.println("1 - 0 =" + (1 - 0));
    }
    //乘法
    @Check
    public void mul(){
        System.out.println("1 * 0 =" + (1 * 0));
    }
    //除法
    @Check
    public void div(){
        System.out.println("1 / 0 =" + (1 / 0));
    }


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

}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Check {
}
/**
 * 简单的测试框架
 *
 * 当主方法执行后,会自动自行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中
 */
public class TestCheck {


    public static void main(String[] args) throws IOException {
        //1.创建计算器对象
        Calculator c = new Calculator();
        //2.获取字节码文件对象
        Class cls = c.getClass();
        //3.获取所有方法
        Method[] methods = cls.getMethods();

        int number = 0;//出现异常的次数
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));


        for (Method method : methods) {
            //4.判断方法上是否有Check注解
            if(method.isAnnotationPresent(Check.class)){
                //5.有,执行
                try {
                    method.invoke(c);
                } catch (Exception e) {
                    //6.捕获异常

                    //记录到文件中
                    number ++;

                    bw.write(method.getName()+ " 方法出异常了");
                    bw.newLine();
                    bw.write("异常的名称:" + e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常的原因:"+e.getCause().getMessage());
                    bw.newLine();
                    bw.write("--------------------------");
                    bw.newLine();

                }
            }
        }

        bw.write("本次测试一共出现 "+number+" 次异常");

        bw.flush();
        bw.close();



    }

}

Published 41 original articles · won praise 1 · views 550

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/105125723