java 注解使用详解

概述

注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。
作用:
1. 编写文档:通过代码里标识的元数据生成文档【生成文档doc文档】
2. 代码分析:通过代码里标识的元数据对代码进行分析【使用反射】
3. 编译检查:通过代码里标识的元数据让编译器能够实现基本的编译检查【Override】

注解介绍:

jdk内置注解:

在java.lang包下,JAVA提供了5个基本注解:
@Override
限定重写父类方法。对于子类中被@Override 修饰的方法,如果存在对应的被重写的父类方法,则正确;如果不存在,则报错。@Override 只能作用于方法,不能作用于其他程序元素。
@Deprecated
用于表示某个程序元素(类、方法等)已过时。如果使用了被@Deprecated修饰的类或方法等,编译器会发出警告。
@SuppressWarnings
抑制编译器警告。指示被@SuppressWarnings修饰的程序元素(以及该程序元素中的所有子元素,例如类以及该类中的方法…..)取消显示指定的编译器警告。例如,常见的@SuppressWarnings(”unchecked”)
SuppressWarnings注解的常见参数值的简单说明:
1、deprecation:使用了不赞成使用的类或方法时的警告(使用@Deprecated使得编译器产生的警告);
2、unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型; 关闭编译器警告
3、allthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告;
4、path:在类路径、源文件路径等中有不存在的路径时的警告;
5、serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告;
6、finally:任何 finally 子句不能正常完成时的警告;
7、all:关于以上所有情况的警告。
@SafeVarargs
@SafeVarargs是JDK 7 专门为抑制“堆污染”警告提供的。

元注解说明:

点击jdk自带注解(SuppressWarnings)查看源码如下:

package java.lang;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {

    String[] value();
}

通过源码我们发现@Target()和@Retention()两个注解为定义注解SuppressWarings使用的注解,我们称这两个为元注解。
通过我们查jdk文档发现,jdk常用的注解为四个,这四个注解的功能和使用说明如下表:

名称 说明
@Target ElementType.METHOD(更多值见下面ElementType类) 指定注解的作用域,class存在于类和接口上,Field作用于变量,Method作用于方法。
@Retention RetentionPolicy.RUNTIME (更多值见下面ElementType类) 指定注解的存在周期,Source注解信息只在源码中存在;Class注解信息存在源码,字节码;RunTime注解信息存在源码,字节码,和运行时。
@Inherited 指定该注解在父类使用的时候,子类会继成该注解。
@Documented 该注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中.

jdk1.8 ElemenType枚举类

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Formal parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE,
    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,
    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

RetentionPolicy 类源码

package java.lang.annotation;

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,
    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}
自定义注解:

自定义注解类编写的一些规则:
1. Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。
2. 参数成员只能用public或默认(default)这两个访问权修饰。
3. 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组.。
4. 注解也可以没有定义成员。
自定义注解需要使用到元注解,获取注解信息可以通过APT(Annotation Processing Tool)获取。在jdk中也可以通过反射获取@Retention为RetentionPolicy.RUNTIME(运行期间)的注解信息。

反射获取注解信息:

自定义注解:RStudent.java

package anno;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface RStudent {

    int _id() default 0;

    String _name() default "";

    String _address() default "";

}

javaBean文件:

package model;

import anno.RStudent;

@RStudent(_id =1,_name="zhangwenwen",_address="beijing")
public class Student {

    public int id;

    public String name;

    public String address;


}

测试代码:

package main;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


import model.Student;
/**
 * 
 * @author 53048
 *
 */
public class TestReflection {


    public static void main(String args []){

        //反射获取注解
        testAnno(Student.class);


    }


    private static <T> void testAnno(Class<T> classs) {
        // TODO Auto-generated method stub
        System.out.println("------------------------------------------------------------------------");
        System.out.println("测试注解:");
        T object = null;
        try {
            object = classs.newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

         Annotation[] annos = classs.getDeclaredAnnotations();

        for(Annotation anno:annos){
            System.out.println(anno);
            if(anno instanceof RStudent){

                RStudent students = (RStudent)anno;
                Student stu= (Student)object;
                stu.id = students._id();
                stu.address = students._address();
                stu.name = students._name();

                System.out.println("学生的Id:"+stu.id);
                System.out.println("学生的name:"+stu.name);
                System.out.println("学生的address:"+stu.address);

            }
        }
    }

这里写图片描述

希望对您有所帮助!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章