Java语言之注解Annotation

2022-06-23 14:35:38

一,概述

1,注解(Annotation)概念:
也叫元数据,一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。
目的:注解就是为了简化开发,避免写过多的代码,不利于程序的扩展以及维护。
2,注解分类:
编写文档:通过代码里标识的注解生成文档【生成文档doc文档】
代码分析:通过代码里标识的注解对代码进行分析,如测试代码【使用反射】
编译检查:通过代码里标识的注解让编译器能够实现基本的编译检查【Override】

二,预定义的注解

主要有以下三个:
1,@Override: 限定重写父类方法。对于子类中@Override 修饰的方法,如果存在对应的被重写的父类方法,则正确;如果不存在,则报错。@Override 只能作用于方法,不能作用于其他程序元素。
2,@Deprecated:用于表示某个程序元素(类、方法等)已过时。如果使用了被@Deprecated修饰的类或方法等,编译器会发出警告。
3,@SuppressWarnnings:抑制编译器警告,一般传入参数“all”,即@SupressWarnnings(“all”)

三,自定义注解

一,格式:

元注解public @interface 注解名{}

二,本质:注解本质是一个接口,接口默认继承Annotation接口。

publicinterfaceMyAnnoextendsjava.lang.annotation.Annotation{}

三,属性:接口中的抽象方法
要求:
1,返回值类型为基本数据类型、String、枚举、注解或以上类型的数组。
2,定义了属性,使用时需给属性赋值,也可在定义时使用default进行默认赋值。
3, 数组赋值时,值使用{}包裹。如果数组中只有一个值,则{}可以省略。

四,元注解
概念:用于描述注解的注解。
自带的元注解:
1,@Target:描述注解能作用的位置。
参数中ElementType取值:
ElementType.TYPE:可以作用于类上;
ElementType.METHOD:可以作用于方法上;
ElementType.FIELD:可以作用于成员变量上。

2,@Rentation:描述注解被保留到的阶段。
参数RetentionPolicy的取值:
RetentionPolicy.SOURCE:当前被描述的注解,会保留到class字节码文件中,并被JVM读取到;
RetentionPolicy.CLASS:保留到字节码文件中;
RetentionPolicy.RUNTIME:保留到源文件当中。

3,@Documened:描述注解是否被抽取到api文档中。
4,@Inherited:描述注解是否被子类继承。

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interfaceMyAnno{intvalue();
    Stringname();
    MyAnno2anno2();
    Personper()default Person.p2;

    String[]strs();}publicenum Person{
    p1,p2;}public @interfaceMyAnno2{}
publicclassDemo1Annotation{@MyAnno(value=12,name="小明", per= Person.p2, anno2=@MyAnno2, strs={"aa","bb"})publicvoidshow1(){}//@MyAnno(13)//当注解中仅有一个value属性时publicvoidshow2(){}}

四,解析注解

获取注解中定义的属性值,即为使用(解析)注解。
步骤:
1,获取注解定义的位置(类、方法、变量)的对象;
2,获取指定的注解对象;
3,调用注解中的抽象方法获取配置中的属性值。

程序:用注解配置类名及方法名,自动执行类中的方法。

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

    StringclassName();
    StringmethodName();}
@Pro(className="Month_06.Day_01.reflect.Student",methodName="sleep")publicclassReflectTest{publicstaticvoidmain(String[] args)throws Exception{//获取字节码文件对象
        Class<ReflectTest> reflectTestClass= ReflectTest.class;//获取文件对象的注解
        Pro anno= reflectTestClass.getAnnotation(Pro.class);//调用注解中的抽象方法
        String className= anno.className();
        String methodName= anno.methodName();

        System.out.println(className+"->"+methodName);//Month_06.Day_01.reflect.Student->sleep

        Classcls= Class.forName(className);
        Object o= cls.newInstance();
        Method method= cls.getMethod(methodName);
        method.invoke(o);//睡}}

五,注解测试方法综合案例

程序需求:在方法上使用注解@Check,测试类CheckTest执行被测试的各个方法,并测试各个方法,将测试结果写入Bug.txt。

import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interfaceCheck{}publicclassCalculator{@Checkpublicvoidadd(){int num=12+15;
        System.out.println("add:"+num);}@Checkpublicvoidsub(){int num=12-15;
        System.out.println("add:"+num);}@Checkpublicvoidmul(){
        String str= null;
        str.toString();int num=12*15;
        System.out.println("add:"+num);}@Checkpublicvoiddiv(){int num=13/0;
        System.out.println("add:"+num);}}
import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.lang.reflect.Method;publicclassTestCheck{publicstaticvoidmain(String[] args)throws IOException{
        Calculator c=newCalculator();
        Classcls= c.getClass();
        BufferedWriter bw=newBufferedWriter(newFileWriter("Bug.txt"));int num=0;

        Method[] methods= cls.getMethods();for(Method method: methods){if(method.isAnnotationPresent(Check.class)){try{
                    method.invoke(c);}catch(Exception e){
                    num++;
                    bw.write(num+","+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("此次测试共有"+num+"个方法产生异常");
        bw.flush();
        bw.close();}}

在这里插入图片描述

  • 作者:X@W
  • 原文链接:https://blog.csdn.net/weixin_43529573/article/details/106590841
    更新时间:2022-06-23 14:35:38