Annotations:注解

注解,作为元数据的一种形式,虽不是程序的一部分,却有以下作用:

可以让编译器跳过某些检测

某些工具可以根据注解信息生成文档等

某些注解可以在运行时检查

@表示这是一个注解

@Override

 注解可以包含元素,可以有值

@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
  只有一个元素时可以没有名字
@SuppressWarnings("unchecked")
 

没有元素时可以没有括号

@Author(name = "Jane Doe")
@EBook
注解也可以有多个,规范做法是每个都单独一行

在JDK8以后,可以有重复注解:

@Author(name = "Jane Doe")
@Author(name = "John Smith")
 

注解的类型在java.lang 或java.lang.annotation

也可以自定义自己的注解类型

注解通常用在定义的地方,类,字段,方法等

在JDK8以后,注解也能作为类型,称为type annotation

以前,注解是来替代注释的

首先要定义

import java.lang.annotation.*;
@Documented  //前面加这个可以让生成的javadoc包括这个注解信息
@interface ClassPreamble { //前面是@interface , 其实注解都是接口,而且定义时也类似接口
String author(); //元素定义 
String date(); int currentRevision() default 1; //默认值 
String lastModified() default "N/A"; 
String lastModifiedBy() default "N/A"; 
// Note use of array 
String[] reviewers();}

定义以后就可以使用了

@ClassPreamble (  //直接@注解类型
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
 

java.lang中的也就是预定义注解

@Deprecated是已过期,编译器会警告

@Override表示这是个覆盖的方法,其实不写也行,通常是个强制性提示,覆盖的不对会报错

@SuppressWarnings("deprecation")让编译器忽略某个警告

编译警告通常有两种,deprecationunchecked,unchecked会提示那些在泛型发明以前写的代码

@SuppressWarnings({"unchecked", "deprecation"})//可以写多个

@SafeVarargs@FunctionalInterface ( 新)

有的注解是用于其他注解的,这称为元注解,通常在java.lang.annotation

@Retention

@Documented

@Target

@Inherited

@Repeatable

原文地址:https://www.cnblogs.com/gcg0036/p/4143611.html