一、注解的定义
public @interface myannotations{属性列表;}@interface 实际表示注解继承 Annotation
可以参考:https://www.zhihu.com/question/47449512
package java.lang.annotation;public interface Annotation {boolean equals(Object obj);int hashCode();String toString();Class<? extends Annotation> annotationType();}
二、注解的类型
主要有三类:
自定义注解: JDK内置注解:如:override 第三方框架提供的注解:如:Spring中 Atuowired
2.1 自带的注解
@Deprecated -- @Deprecated 所标注内容,不再被建议使用。@Override -- @Override 只能标注方法,表示该方法覆盖父类中的方法。@Documented -- @Documented 所标注内容,可以出现在javadoc中。@Inherited -- @Inherited只能被用来标注“Annotation类型”,它所标注的Annotation具有继承性。@Retention -- @Retention只能被用来标注“Annotation类型”,而且它被用来指定Annotation的RetentionPolicy属性。@Target -- @Target只能被用来标注“Annotation类型”,而且它被用来指定Annotation的ElementType属性。@SuppressWarnings -- @SuppressWarnings 所标注内容产生的警告,编译器会对这些警告保持静默。
重要的元注解(用来修饰注解的注解)
ElementType:指定注解的类型。
package java.lang.annotation;public enum ElementType {TYPE, /* 类、接口(包括注释类型)或枚举声明 */FIELD, /* 字段声明(包括枚举常量) */METHOD, /* 方法声明 */PARAMETER, /* 参数声明 */CONSTRUCTOR, /* 构造方法声明 */LOCAL_VARIABLE, /* 局部变量声明 */ANNOTATION_TYPE, /* 注释类型声明 */PACKAGE /* 包声明 */}
RetentionPolicy:用来指定注解的作用域。
package java.lang.annotation;public enum RetentionPolicy {SOURCE, /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 */CLASS, /* 编译器将Annotation存储于类对应的.class文件中。默认行为 */RUNTIME /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */}
例子:定义一个可以修饰类、方法的注解,且该注解可以在运行时生效。
@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation{}
2.2 第三方注解
Spring Autowired注解,判断是否需要自动装置。
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Autowired {boolean required() default true;}
三、使用与作用
3.1 编译检查
如:@SuppressWarnings、@Deprecated 等
3.2 反射中使用注解
通过反射判断是否包含某些注解,然后进行相应的操作。
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface PrintDate {String value() default "20210503";}@PrintDate(value="20210603")public class AnnotationClass1 {public String toString(){return "AnnotationClass1";}}import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class AnnotationTest {public static void main(String args[]){AnnotationClass1 class1 = new AnnotationClass1();Annotation[] annotations = class1.getClass().getDeclaredAnnotations();// 判断类是否包含注解if(class1.getClass().isAnnotationPresent(PrintDate.class)){System.out.println(class1);}for(Annotation annotation : annotations){System.out.println(annotation+" : "+((PrintDate)annotation).value());}}}
注意:方法、类都可以得到注解Class<?>.getDeclaredAnnotations();Method.getDeclaredAnnotations();
