Java 高级_注解 Annotation

143 阅读7分钟

注解的使用

主要内容:

  • 注解(Annotation)概念
  • 常见的 Annotation 示例
  • 自定义 Annotation
  • JDK 中的元注解
  • 利用反射获取注解信息(在反射部分涉及)
  • JDK 8 中注解的新特性

注解概述

  • 从 JDK5.0开始,Java增加了对元数据(MetaData)的支持,也就是 Annotation
  • Annotation其实就是代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理;通过使用 Annotation,程序员可以在不改变原有逻辑情况下,在源文件中嵌入一些补充信息;代码分析工具、开发工具和部署工具可以通过这些补充信息进行验证或者进行部署
  • Annotation可以像修饰符一样被使用,可以用于修饰 包、类、构造器、方法、成员变量、参数、局部变量的声明,这些信息被保存在 Annotation的 “name = value”对中
  • 在JavaSE中,注解的使用目的比较简单,如标记过时功能、忽略警告等;在JavaEE/Android中注解占据更重要的角色,如用来配置应用程序的任何切面,代替JavaEE旧版本中所遗留的繁冗代码和 XML配置等
  • 未来的开发模式都是基于注解的,JPA是基于注解的,Spring2.5以上都是基于注解的,Hibernate3.X以后也是基于注解的,现在的 Struts2有一部分也是基于注解的了,注解是一种趋势,一定程度上可以说:框架 = 注解 + 反射(读取操作注解...) + 设计模式
  • 使用 Annotation 时要在其前面增加 @ 符号,并把 Annotation当成一个修饰符使用;用于修饰它支持的程序元素

示例一:生成文档相关的注解

  • @author:标明开发此类模块的作者
  • @version:标明该类模块的版本
  • @see:主题内容
  • @since:起始版本
  • @param:对方法中参数的说明
  • @return:对方法返回值的说明
  • @exception:对方法可能抛出的异常进行说明

格式要求

  1. @param 形参名 形参类型 形参说明
  2. @return 返回值类型 返回值说明
  3. @exception 异常类型 异常说明

实例二:在编译时进行格式检查(JDK内置的三个基本注解)

  • @Override:限定重写父类方法,只能用于方法
  • @Deprecated:用于表示所修饰的元素(类、方法等)
  • @SuppressWarnings:抑制编译器警告

实例三:跟踪代码依赖性,实现替代配置文件功能

  • Servlet3.0提供了注解,使得不再需要在 web.xml文件中进行 Servlet的部署
  • Spring框架中关于‘事务’的管理

自定义注解

参照 @SuppressWarnings 源码

/*
 * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */

package java.lang;

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

/**
 * Indicates that the named compiler warnings should be suppressed in the
 * annotated element (and in all program elements contained in the annotated
 * element).  Note that the set of warnings suppressed in a given element is
 * a superset of the warnings suppressed in all containing elements.  For
 * example, if you annotate a class to suppress one warning and annotate a
 * method to suppress another, both warnings will be suppressed in the method.
 *
 * <p>As a matter of style, programmers should always use this annotation
 * on the most deeply nested element where it is effective.  If you want to
 * suppress a warning in a particular method, you should annotate that
 * method rather than its class.
 *
 * @author Josh Bloch
 * @since 1.5
 * @jls 4.8 Raw Types
 * @jls 4.12.2 Variables of Reference Type
 * @jls 5.1.9 Unchecked Conversion
 * @jls 5.5.2 Checked Casts and Unchecked Casts
 * @jls 9.6.3.5 @SuppressWarnings
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)

public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p> The string {@code "unchecked"} is used to suppress
     * unchecked warnings. Compiler vendors should document the
     * additional warning names they support in conjunction with this
     * annotation type. They are encouraged to cooperate to ensure
     * that the same names work across multiple compilers.
     * @return the set of warnings to be suppressed
     */
     // 属性
    String[] value();
}

自定义

  • 定义新的 Annotation 类型使用 @interface 关键字

  • 自定义注解自动继承了 java.lang.annotation.Annotation 接口

  • Annotation 的成员变量在 Annotation 定义中以无参数方法的形式来声明;其方法名和返回值定义了该成员的名字和类型;我们称为配置参数;类型只能是 八种基本数据类型、String类型、Class类型、enum类型、Annotation类型、以上所有类型的数组

  • 可以在定义 Annotation 的成员变量时为其指定初始值,指定成员变量的初始值可以使用 default 关键字

  • 如果只有一个参数成员,建议使用参数名为value

  • 如果定义的注解含有配置参数,那么使用时必须指定参数值,除非它有默认值;格式是 “参数名 = 参数值”,如果只有一个参数成员,且名称为 value,可以省略 “value = ”

  • 没有成员定义的 Annotation 称为 标记;包含成员变量的 Annotation 称为元数据 Annotation

  • 注:自定义的注解,必须配上注解的信息处理流程(使用反射)才有意义

JDK 中的元注解

应用最多的元注解是:@Retention、@Target

元注解:用于 修饰其它注解的 注解

  • JDK 的元 Annotation 用于修饰其它 Annotation 定义

  • JDK5.0提供了4个标准的 meta-annotation类型,分别是:

    1. Retention
    2. Target
    3. Documented
    4. Inherited

数据库中 元数据的理解:对 现有数据修饰的 数据

  • String name = "atguigu"

Retention

@Retention:只能用于修饰 Annotation定义的,用于指定该 Annotation的生命周期,@Retention 包含一个 RetentionPolicy 类型的成员变量,使用 @Retention 时必须为该 value成员变量指定值:

  1. RetentionPolicy.SOURCE:在源文件中有效(源文件保留),编译器直接丢弃这种策略的注释。
  2. RetentionPolicy.CLASS:在class文件中有效(class保留),当运行Java程序时,JVM不会保留注释;这是默认值。
  3. RetentionPolicy.RUNTIME:在运行时有效(运行时保留),当运行Java程序时,JVM会保留注释;程序可以通过反射获取该注释。

Target

@Target:用于修饰 Annotation 定义的,用于指定被修饰的 Annotation 能用于修饰哪些程序元素;@Target 也包含一个名为 value 的成员变量

  1. CONSTRUCTOR:用于描述构造器
  2. FIELD:用于描述域
  3. LOCAL_VARIABLE:用于描述局部变量
  4. METHOD:用于描述方法
  5. PACKAGE:用于描述包
  6. PARAMETER:用于描述参数
  7. TYPE:用于描述 类、接口(包括注解类型)、 enum声明

Documented

@Documented:用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档;默认情况下,javadoc 是不包括注解的

  • 定义为 Documented 的注解必须设置 Retention 值为 RUNTIME

Inherited

@Inherited:被它修饰的 Annotation 将具有 继承性;如果某个类使用了被 @Inherited 修饰的 Annotation,则其子类将自动具有该注解

  • 比如:如果把标有 @Inherited 注解的自定义的注解标注在类级别上,子类则可以继承父类级别的注解
  • 实际应用中,使用较少

jdk8 中注解的新特性:

可重复注解

  1. 在 MyAnnotation上声明 @Repeatable,成员值为 MyAnnotations.class
  2. MyAnnotation上的 Target、Retention和 MyAnnotations相同
package com.atguigu.java1;

import java.lang.annotation.*;

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

/**
 * @author lv
 * @create 2020-12-20 11:06
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Inherited
@Repeatable(MyAnnotations.class)

public @interface MyAnnotation {
    String value() default "hello";
}

// ********************************

package com.atguigu.java1;

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

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

/**
 * @author lv
 * @create 2020-12-20 16:05
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})

public @interface MyAnnotations {
    MyAnnotation[] value();
}

// *******************************

package com.atguigu.java1;

import org.junit.Test;

import java.lang.annotation.Annotation;

/**
 * Annotation
 *
 * 1.如何自定义注解:参照@SuppressWarnings去定义
 *
 * 2.jdk 提供的4种元注解
 *
 * Retention:指定所修饰的 Annotation的生命周期
 * Target:指定被修饰的 Annotation能用于修饰哪些程序元素
 * Documented:表示所修饰的注解在被 javadoc解析时,保留下来
 * Inherited:被它修饰的 Annotation将具有继承性
 *
 * 3.通过反射获取注解信息 --> 到反射内容时系统讲解
 *
 * 4. jdk8 中注解的新特性:
 *
 * 4.1 可重复注解
 *
 * 4.2 类型注解
 *
 * @author lv
 * @create 2020-12-20 10:36
 */
public class AnnotationTest {
    public static void main(String[] args) {
        Person p1 = new Student(); // 多态
        p1.walk(); // student walk
    }

    @Test
    public void testAnnotation() {
        // test Inherited
        Class cls = Student.class;
        Annotation[] ans = cls.getAnnotations();
        for (int i = 0; i < ans.length; i++) {
            System.out.println(ans[i]); // @com.atguigu.java1.MyAnnotation(value=hello)
        }
    }
}

//@MyAnnotation(value = "world")
//@MyAnnotation // default 默认值
// jdk8 之前的写法
//@MyAnnotations({@MyAnnotation(value = "world"), @MyAnnotation(value = "hi")})

// jdk8 之后
@MyAnnotation(value = "world1")
@MyAnnotation(value = "world2")

class Person {
    public String name;
    public int age;

    public Person() {

    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void walk() {
        @SuppressWarnings("unused")
        int value = 0;
        System.out.println("person walk");
    }

}

interface Info {
    void show();
}

class Student extends Person implements Info {
    @Override
    public void walk() {
        System.out.println("student walk");
    }

    @Override
    public void show() {
        System.out.println("Student");
    }
}

类型注解

  1. ElementType.TYPE_PARAMETER:表示该注解能写在类型变量的声明语句中
  2. ElementType.TYPE_USE:表示该注解能写在使用类型的任何语句中