学懂注解(参考官方文档)

182 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第24天,点击查看活动详情

Java注解

一、注的解概述(Annotation)

(1) 大概是什么

Annotations, a form of metadata(元数据), provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

注解是元数据的一种形式,用于提供与程序相关的数据,但这些数据并不是程序的一部分。注解对它们所注释的代码的操作没有直接影响。

(2) 注解的用处

  1. Annotations can be used by the compiler to detect errors or suppress warnings.

注解可以为编译器使用,用于检测错误或抑制警告

  1. 【Compile-time and deployment-time processing】Software tools can process annotation information to generate code, XML files, and so forth.

【运行时和部署的时候】软件工具可以通过处理注解信息生成 Java 代码、生成 XML 文件等等 …

  1. 【Runtime processing】Some annotations are available to be examined at runtime.

有些注解可在运行时被检测到

二、注解基础

(1) 注解的基本格式

In its simplest form, an annotation looks like the following:

一个注解最简单的格式如下所示:

@Entity

The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation’s name is Override:

@ 符号用于告诉编译器 @ 符号后面的内容是一个注解。在下面的例子中,注解的名字是:Override

class Dog extends Animal {
    @Override
    public void test() {
        super.test();
    }
}

The annotation can include elements, which can be named or unnamed, and there are values for those elements:

注解可以包含元素。元素可以有名字,也可以没有名字。元素如下代码所示:

@Author(
        name = "庆医",
        date = "2022/5/20"
)
class CommonClass { 
    
}

上面代码中的 name 和 date 是注解的元素

【庆医】和【2022/5/20】是元素的值

@SuppressWarnings(value = "unused")
class Whatever {
    private String s;
}


上面代码中的  @  告诉编译器  @  符号后面的是注解

SuppressWarnings 是注解名

value 是 SuppressWarnings 注解的元素

【unused】是 value 元素的值

If there is just one element named value, then the name can be omitted.

如果注解中只写了一个元素,并且元素的名字是 value,那么元素名可以省略掉(如下代码所示)

//@SuppressWarnings(value = "unused")
@SuppressWarnings("unused")
class Whatever {
    private String s;
}

If the annotation has no elements, then the parentheses(圆括号) can be omitted.

如果注解中没有元素,那么注解的圆括号可以省略掉

It is also possible to use multiple annotations on the same declaration.
也可以在同一个声明上使用多个注解

class Dog extends Animal {

    @Override
    @SuppressWarnings("unused")
    public void test() {
        int a = 66;
        super.test();
    }

}

(2) 注解可以使用在哪儿

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

注解可以运用于声明:类声明、字段声明、方法声明和其他程序元素的声明。当多个注解使用在同一个声明的时候,每一个注解独占一行。