1.常见的注解
@Deprecated表示过时的方法,不建议被使用的注解。
@Deprecated public void method(){ System.out.println("method()"); }
@SuppressWarnings 压制警告的注解,一般的黄色小灯泡就是警告,处理了就多出来这个注解了。
@Override重写表示这是一个重写的方法,是否符合语法规范。
@Override public String toString() { return "OverrideAnnotation"; }
2.用户自定义注解,定义:
public @interface MyAnnotation { String value2() default "a"; boolean value1(); }
使用:在方法,类,变量前面直接用就行了,如果自定义的只有一个value,可以省略不写(vlaue=)@MyAnnotation("value");
@MyAnnotation(value2="my",value1=false) public class test2 { @MyAnnotation(value2="my",value1=false) int i=0; @MyAnnotation(value2="my",value1=false) public String toString() { return super.toString(); } }
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) public @interface MyAnnotation { String value(); }
@Target, @Retention是注解的注解,对自定义注解的进一步解释。
@Target(ElementType.TYPE) 指示注释类型所适用的程序元素的种类。
ElementType必要元素,
枚举常量摘要 :
ANNOTATION_TYPE :注释类型声明
CONSTRUCTOR : 构造方法声明
FIELD : 字段声明(包括枚举常量)
LOCAL_VARIABLE: 局部变量声明
METHOD : 方法声明
PACKAGE : 包声明
PARAMETER: 参数声明
TYPE : 类、接口(包括注释类型)或枚举声明
@Retention(RetentionPolicy.RUNTIME)
指示注释类型的注释要保留多久。RetentionPolicy必要元素:
Class表示保存类文件,不保留注释。
Runtime表示保存类文件并且保留注释。//这里的运行时很关键,不是这个通过反射机制无法读取注解的类
Source表示丢弃的注释。