Java注解详解

有些同学向我反映,Java注解老是整不明白,那么笔者就专门写篇文章来带同学们学习学习,顺便笔者也复习一下。

Java注解详解

Java中的注解可不是注释,注意区别。Java注解是跟编译器直接挂钩,在JDK1.5之后就出现了注解,那么注解究竟是干嘛的呢?开发者把它开发出来是为了干什么的呢?

1.生成文档。这是最常见的,也是java 最早提供的注解。常用的有@see @param @return 等,这点都很熟悉,不就是生成自己的API嘛。

2.跟踪代码依赖性,实现替代配置文件功能。比较常见的是spring 2.5 开始的基于注解配置。作用就是减少配置。现在的框架基本都使用了这种配置来减少配置文件的数量。

3.在编译时进行格式检查。如@Override 放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出。

所以要想成为一名优秀的Java开发程序员,注解的掌握那是必须的。

1.Java中自带的注解

@Override
子类对父类方法的重写所带的注解,这个笔者就不多说啦!简单

@Deprecated
表示已经过时,不建议使用,但是依然可以使用

比如你在调用Thread类的stop方法的时候出现一条横杠,这就是加了@Deprecated的效果,我截个图给你看看:

这条杠是编译器告诉你此方法已经过时啦,所以加条杠提示你一下,但是依然可以调用,并不是不能使用,而是建议不要使用。

@SuppressWarnings
用来抑制编译时的警告信息,编译器在你写代码的时候,难免会出现很多的警告,有强迫症的程序猿会感到极其不爽,那么肿么办呢?@SuppressWarnings注解就可以告诉编译器,别警告啦,代码不会有问题的。

比如你想把调用Thread的stop方法的警告去掉,那么你就可以这么写:

有的同学可能不理解@SuppressWarnings(“all”)中的"all"是啥意思?其实很简单,@SuppressWarnings注解一定要传递一个参数给它,来表示过滤掉哪些类型的警告,笔者添加了"all"表示过滤掉所有类型的警告,很好理解吧!那么还可以传递什么参数来过滤警告呢?看看下面的表格你就会知道啦:

还有一些其它的Java自带注解,笔者就不一一说明了。

2.自定义注解

在学会自定义注解之前,我们必须先来理解一下Java当中用来给自定义注解而注解的元注解,有点绕口哈!没关系,其实很简单,就是说你要自定义一个注解,你必须说明一下这个自定义的注解的使用范围以及保存注解信息,还有是否包含于Javadoc中,是否允许子类继承父类中的注解。这4点分别对应这4种元注解,看下面的表格你就懂啦:
Java 4种元注解表格

自定义注解使用关键字@interface,这跟接口有点像,只不过一个"@"符号的差别,还有就是Java注解不支持继承,示例代码如下:

@Target(value = {ElementType.METHOD})//这里表示此注解只能被使用于方法
@Retention(RetentionPolicy.RUNTIME)//通常默认使用RUNTIME
@Documented
@Inherited
public @interface MyAnnotation {

    /*注意在注解当中属性声明是:
    * 类型 + 属性名();
    * 不是声明一个方法,这一定要区别开来
    */
    String str();//注解的属性声明,属性类型为String,名字是"str"

}

参考元注解表格,使用"@interface"关键字声明,注意属性的声明末尾是有"()"的。还有一点就是注解的元素(属性)只支持:

1.所有的基本类型
2.String
3.Class
4.enum
5.Annotation
6.String[],Class[],enum[],Annotation[]以及基本类型数组
其他的类型都会报错

学会声明了,那么如何使用这个注解呢?示例代码如下:

//@MyAnnotation(str = "王者荣耀")  用在声明类这里是报错的,因为笔者的注解@MyAnnotation只能用于方法
public class Student {

    public String name;
    public int    age;

    @MyAnnotation(str = "王者荣耀") //用在这里不会报错
    public void playAndroidGame(){

        System.out.println(this.name+"玩王者荣耀!");

    }

}

目前的注解好像用途并没有完全体现出来,因为你没有为注解添加注解处理器,没有添加注解处理器的注解跟注释没任何区别,所以我们必须为注解添加一个注解处理器,才能让注解的真正用途体现出来,这需要反射的知识,如果你对反射不熟,那么注解处理器怕是有些困难。

不熟悉的同学,通过下面的链接来学习一下反射:
http://blog.csdn.net/briblue/article/details/74616922?locationNum=3&fps=1

3.通过反射创建和使用注解器

讲解注解器需要一个实例作为参考,我们来设计这么一个注解器,可以通过注解器来获取某个类的所有信息。一个类里面会存在属性,方法,内部类,构造函数等,那么我们如何通过注解的方式去获取到一个类的所有信息呢?首先来设计我们的注解:

类的注解:元素(属性)仅包含类名

@Target(value = ElementType.TYPE) //使用范围类,接口,enum等
// 要想通过反射获取这个注解信息,此注解一定要保留于运行期,所以这里@@Retention必须是RUNTIME的
@Retention(RetentionPolicy.RUNTIME)
public @interface ClassAnnotation {

    String className();//类的名字

}

类的属性的注解:元素(属性)包含–> 属性名,访问权限,属性类型

@Target(value = ElementType.FIELD) //使用于类的成员属性
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {

    String fieldName();//属性的名字
    String accessPer();//访问权限
    Class fieldType();//属性的类型

}

方法的注解: 元素(属性)包含–> 方法名,参数列表,返回值类型,访问权限,方法的功能

@Target(value = ElementType.METHOD) //使用于方法
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAnnotation {

    String methodName();//方法的名字
    Class[] parameterList();//参数列表
    Class   returnType();//返回值类型
    String accessPer();//访问权限
    String methodFunction();//方法的功能描述

}

构造器的注解: 元素(属性)包含–> 构造器的名名,参数列表,返回值类型,访问权限

@Target(value = ElementType.CONSTRUCTOR) //使用于构造器
@Retention(RetentionPolicy.RUNTIME)
public @interface ConstructorAnnotation {

    String conName();//构造器的名字
    Class[] parameterList();//参数列表
    Class   returnType();//返回值类型
    String accessPer();//访问权限

}

注解已经定义完成,下面一步就是将注解应用于一个类当中,示例代码如下:

import Date20170810.Annotation.ClassAnnotation;
import Date20170810.Annotation.ConstructorAnnotation;
import Date20170810.Annotation.FieldAnnotation;
import Date20170810.Annotation.MethodAnnotation;

@ClassAnnotation(className = "Studnet")
public class Student {

    @FieldAnnotation(fieldName = "name",accessPer = "private",fieldType = "String")
    private String name = "";

    @FieldAnnotation(fieldName = "age",accessPer = "private",fieldType = "int")
    private int age = 0;

    @ConstructorAnnotation(methodName = "Studnet", parameterList = {String.class,int.class},
            returnType = Student.class, accessPer = "public" )
    public Student(String name,int age){

        this.age = age;
        this.name = name;

    }

     @MethodAnnotation(methodName = "getName",parameterList = {},returnType = String.class,
        accessPer = "public",methodFunction = "返回当前Student实例对象的名字name")
    public String getName(){

        return this.name;

    }

     @MethodAnnotation(methodName = "setName",parameterList = {String.class},returnType = Void.class,
        accessPer = "public",methodFunction = "设置当前Student实例对象的名字name")
    public void setName(String name){
        this.name = name;
    }

     @MethodAnnotation(methodName = "getAge",parameterList = {},returnType = int.class,
        accessPer = "public",methodFunction = "返回当前Student实例对象的年龄age")
    public int getAge(){
        return  this.age;
    }

    @MethodAnnotation(methodName = "setAge",parameterList = {int.class},returnType = Void.class,
        accessPer = "public",methodFunction = "设置当前Student实例对象的年龄age")
    public void setAge(int age){
        this.age = age;
    }


    @MethodAnnotation(methodName = "playAndroidGame",parameterList = {},returnType = Void.class,
        accessPer = "public",methodFunction = "王者荣耀有关,就是对小学生玩王者荣耀太厉害的吐槽!")
    public void playAndroidGame(){

        System.out.println("hello,I'm" + this.name+",今年"+this.age+"岁啦");

        if(this.age >12){

            System.out.println(this.age+"岁,打王者荣耀还可以不算太坑!");

        }else{

            System.out.println("由于是小学生,王者排位就算啦,不如来一盘匹配," +
                "排位万万不可!因为啥?怕排位的时候小学生说我辣鸡!");

        }


    }



}

下面就是通过反射来获取Student类的所有信息啦!示例代码如下:

//注解器
public class AnnotatorDemo {

    //通过反射获取类的注解信息
    public static void getClassAnnotationMessage(Class class1){

        System.out.println("类的注解信息:");
        for(java.lang.annotation.Annotation annotation:class1.getDeclaredAnnotations()){


            System.out.println(annotation);
            //获取类注解属性className的值
            if(annotation.annotationType().equals(ClassAnnotation.class)){
                String className = ((ClassAnnotation)annotation).className();
                System.out.println("类名:"+className);
            }

        }

    }

    //通过反射获取属性的注解信息
    public static void getFieldAnnotationMessage(Class class1){

        System.out.println("属性注解的信息:");

        Field[] fields = class1.getDeclaredFields();

        for(Field field:fields){

            System.out.println();
            FieldAnnotation fieldAnnotation = field.getDeclaredAnnotation(FieldAnnotation.class);
            System.out.println(fieldAnnotation);
            //获取属性注解的各种值
            String fieldName = fieldAnnotation.fieldName();
            System.out.println("属性名:"+fieldName);
            String accessPer = fieldAnnotation.accessPer();
            System.out.println("属性访问权限:"+accessPer);
            Class fieldType = fieldAnnotation.fieldType();
            System.out.println("属性的类型:"+fieldType);

        }

    }

    //获取构造器的注解信息
    public static void getConstrutorAnnotationMessage(Class class1){

        System.out.println("构造器注解的信息:");

       Constructor[] constructors =  class1.getDeclaredConstructors();

       for(Constructor constructor:constructors){

           System.out.println();
           ConstructorAnnotation constructorAnnotation = constructor.getDeclaredAnnotation(ConstructorAnnotation.class);
           System.out.println(constructorAnnotation);

           String conName = constructorAnnotation.conName();
           System.out.println("构造器的名字:"+conName);
           System.out.print("构造器的参数列表:");
           Class[] parameterList = constructorAnnotation.parameterList();
           for(Class c : parameterList){
               System.out.print(" [ "+c.getName()+" ] ");
           }
           System.out.println();
           Class returnType  = constructorAnnotation.returnType();
           System.out.println("返回值类型:"+returnType.getName());
           String accessPer = constructorAnnotation.accessPer();
           System.out.println("访问权限:"+accessPer);

       }

    }


    public static void getMethodAnnotationMessage(Class class1){


        System.out.println("方法注解的信息:");


        Method[] methods = class1.getDeclaredMethods();

        for(Method method:methods){

            System.out.println();
            MethodAnnotation methodAnnotation = method.getDeclaredAnnotation(MethodAnnotation.class);

            System.out.println(methodAnnotation);

            String methodName = methodAnnotation.methodName();
            System.out.println("方法的名字:"+methodName);
            Class[] parameterList = methodAnnotation.parameterList();
            System.out.print("方法参数参数列表:");
            //判断参数列表是否个数为0
            if(parameterList.length == 0){
                 //说明此方法无参
                 System.out.println("无参");

            }else{
                //说明此方法有参
                for(Class c : parameterList){
                
                 System.out.print(" [ "+c.getName()+" ] ");
                
                }
              System.out.println();

            }
            Class returnType = methodAnnotation.returnType();
            System.out.println("方法的返回值类型:"+returnType.getName());
            String accessPer = methodAnnotation.accessPer();
            System.out.println("方法的访问权限:"+accessPer);
            String methodFunction = methodAnnotation.methodFunction();
            System.out.println("方法的功能描述:"+methodFunction);




        }



    }


    public static void main(String[] args){

        Class class_Student = Student.class;

        //得到类注解的信息
        getClassAnnotationMessage(class_Student);

        System.out.println("\n");

        //得到属性注解的信息
        getFieldAnnotationMessage(class_Student);

        System.out.println("\n");

        //得到构造器的注解的信息
        getConstrutorAnnotationMessage(class_Student);

        System.out.println("\n");

        //得到方法的注解的信息
        getMethodAnnotationMessage(class_Student);

    }

}

运行结果:

类的注解信息:  
@Date20170810.Annotation.ClassAnnotation(className=Student)  
类名:Student  


属性注解的信息:  

@Date20170810.Annotation.FieldAnnotation(fieldName=name, accessPer=private, fieldType=class java.lang.String)  
属性名:name  
属性访问权限:private  
属性的类型:class java.lang.String  

@Date20170810.Annotation.FieldAnnotation(fieldName=age, accessPer=private, fieldType=int)  
属性名:age  
属性访问权限:private  
属性的类型:int  


构造器注解的信息:

@Date20170810.Annotation.ConstructorAnnotation(conName=Studnet, parameterList=[class java.lang.String, int], returnType=class Date20170810.Student, accessPer=public)  
构造器的名字:Studnet  
构造器的参数列表: [ java.lang.String ]  [ int ]   
返回值类型:Date20170810.Student  
访问权限:public  


方法注解的信息:  

@Date20170810.Annotation.MethodAnnotation(methodName=getName, parameterList=[], returnType=class java.lang.String, accessPer=public, methodFunction=返回当前Student实例对象的名字name)  
方法的名字:getName  
方法参数参数列表:无参  
方法的返回值类型:java.lang.String  
方法的访问权限:public  
方法的功能描述:返回当前Student实例对象的名字name  

@Date20170810.Annotation.MethodAnnotation(methodName=setName, parameterList=[class java.lang.String], returnType=class java.lang.Void, accessPer=public, methodFunction=设置当前Student实例对象的名字name)  
方法的名字:setName  
方法参数参数列表: [ java.lang.String ]   
方法的返回值类型:java.lang.Void  
方法的访问权限:public  
方法的功能描述:设置当前Student实例对象的名字name  

@Date20170810.Annotation.MethodAnnotation(methodName=setAge, parameterList=[int], returnType=class java.lang.Void, accessPer=public, methodFunction=设置当前Student实例对象的年龄age)  
方法的名字:setAge  
方法参数参数列表: [ int ]   
方法的返回值类型:java.lang.Void  
方法的访问权限:public  
方法的功能描述:设置当前Student实例对象的年龄age  

@Date20170810.Annotation.MethodAnnotation(methodName=playAndroidGame, parameterList=[], returnType=class java.lang.Void, accessPer=public, methodFunction=王者荣耀有关,就是对小学生玩王者荣耀太厉害的吐槽!)  
方法的名字:playAndroidGame  
方法参数参数列表:无参  
方法的返回值类型:java.lang.Void
方法的访问权限:public  
方法的功能描述:王者荣耀有关,就是对小学生玩王者荣耀太厉害的吐槽!  

@Date20170810.Annotation.MethodAnnotation(methodName=getAge, parameterList=[], returnType=int, accessPer=public, methodFunction=返回当前Student实例对象的年龄age)  
方法的名字:getAge  
方法参数参数列表:无参  
方法的返回值类型:int  
方法的访问权限:public  
方法的功能描述:返回当前Student实例对象的年龄age  

一定要自己完成一遍…

搞明白了这个例子,那么你对注解的掌握就完成了一大半,为什么笔者不写其他牛的例子,而只写如何使用注解获取类的所有信息的例子,因为你只要通过注解获取到类的所有信息,那么很多框架,包括自己想写框架,在你一次次写注解的时候,你就慢慢掌握啦!

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java注解处理器(Annotation Processor)是Java语言提供的一种机制,用于在编译时扫描和处理注解信息。它可以自动扫描Java源代码中的注解,生成新的Java代码、XML文件或者其他类型的文件。 Java注解处理器可以用于很多方面,比如生成代码、检查代码、生成文档等等。下面我们来详细介绍一下Java注解处理器的使用。 1. 创建注解 首先,我们需要定义一个注解注解通常用来标记Java源代码中的某个元素,比如类、方法、变量等。注解的定义方式如下: ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface MyAnnotation { String value(); } ``` 上面的代码定义了一个注解`MyAnnotation`,它有一个属性`value`。这个注解只能用于类上,它的生命周期为源代码级别。 2. 编写注解处理器 接下来,我们需要创建一个注解处理器,用来扫描和处理Java源代码中的注解信息。注解处理器必须实现`javax.annotation.processing.Processor`接口,同时还需要用`@SupportedAnnotationTypes`注解指定要处理的注解类型,用`@SupportedSourceVersion`注解指定支持的Java版本。 ```java @SupportedAnnotationTypes("MyAnnotation") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class MyAnnotationProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation); for (Element element : elements) { if (element.getKind() == ElementKind.CLASS) { String className = element.getSimpleName().toString(); String packageName = processingEnv.getElementUtils().getPackageOf(element).toString(); String value = element.getAnnotation(MyAnnotation.class).value(); System.out.println("Found class " + packageName + "." + className + ", value = " + value); } } } return true; } } ``` 上面的代码是一个简单的注解处理器,它可以处理`MyAnnotation`注解,输出被注解的类的信息,包括类名、包名和注解的属性值。 3. 注册注解处理器 最后,我们需要在`META-INF/services/javax.annotation.processing.Processor`文件中注册注解处理器,这样编译器才能够找到它并使用它。这个文件的内容就是注解处理器的全限定类名,比如: ``` com.example.MyAnnotationProcessor ``` 4. 编译Java源代码 现在我们就可以使用注解处理器了。对于一个Java项目,我们需要将注解处理器打包成一个Jar文件,并将它添加到项目的classpath中。然后,在编译Java源代码时,我们需要指定`-processor`选项来告诉编译器要使用哪个注解处理器,比如: ``` javac -cp my-processor.jar -processor com.example.MyAnnotationProcessor MyAnnotatedClass.java ``` 上面的命令将会编译`MyAnnotatedClass.java`文件,并使用`com.example.MyAnnotationProcessor`注解处理器来处理其中的注解信息。 总结 Java注解处理器是一个非常强大的工具,它可以帮助我们自动化生成代码、检查代码、生成文档等等。使用注解处理器可以减少手写重复代码的工作量,提高代码的可维护性和可读性。需要注意的是,注解处理器只能用于编译时,不能用于运行时。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值