Java 注解从 JDK5 开始支持加入源代码的特殊语法元数据
1. 内置注解
- @Override - 检查该方法是否是重写方法,如果父类 / 实现的接口中不存在该方法时,会提示编译错误 
- @Deprecated - 标记过时的方法,如果使用被标记为此注解的方法,会提示便衣警告。 
- @SuppressWarnings - 镇压警告,使编译器忽略注解声明中的警告 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 
 | public class Test01 extends Object{
 @Override
 public String toString() {
 
 return super.toString();
 }
 
 @Deprecated
 public static void test(){
 System.out.println("Deprecated");
 }
 
 @SuppressWarnings("all")
 public void test02(){
 List list = new ArrayList();
 }
 
 public static void main(String[] args) {
 test();
 }
 }
 
 | 
2. 自定义注解
格式:@interface 自定义注解名
作用在自定义注解上的注解
- @Target - 标记注解的使用范围 - ElementType.TYPE /ElementType.FIELD /ElementType.METHOD /ElementType.PARAMETER/ElementType.CONSTRUCTOR等等
 
- @Retention - 标记注解在什么范围内有效 - RetentionPolicy.RUNTIME > RetentionPolicy.CLASS > RetentionPolicy.SOURCE
 
- @Document - 标记注解是否包含在用户文档中 
- @Inherited - 标记这个注解类继承于哪个注解类 
自 Java 7 新增注解
- @SafeVarargs - Java 7 开始支持, 忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告 
- @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。 
- @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | import java.lang.annotation.*;
 
 @MyAnnotation
 public class Test02 {
 
 @MyAnnotation
 public void test() {
 
 }
 
 }
 
 
 
 @Target(value = {ElementType.METHOD, ElementType.TYPE})
 
 @Retention(value = RetentionPolicy.RUNTIME)
 
 @Documented
 
 @Inherited
 @interface MyAnnotation {
 }
 
 | 
3. 自定义注解的其他
- 注解内定义含义 参数类型  参数名();
- 注解可以显式赋值, 如果没有默认值,就必须给注解赋值(默认值设置方法:参数类型  参数名() DEFAULT 默认值; )
- 如果注解内只有一个值,通常设置为value,并且在使用过程中,value可以不需显式赋值
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | import java.lang.annotation.ElementType;import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
 public class Test03 {
 
 @MyAnnotation2(name = "Hello", schools = "MIT")
 public void test(){
 
 }
 
 @MyAnnotation3("who")
 public void test2(){
 
 }
 }
 
 
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation2 {
 String name() default "";
 int age() default 0;
 int id() default -1;
 
 String[] schools() default {"MIT", "HARWARD"};
 }
 
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation3 {
 String value();
 }
 
 |