JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)

转载自 JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)

JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


jdk1.5起开始提供了4个元注解,用来定义自定义注解的注解,它们分别是:


@Target


指定注解使用的目标范围(类、方法、字段等),其参考值见类的定义:java.lang.annotation.ElementType


@Documented


指定被标注的注解会包含在javadoc中。


@Retention


指定注解的生命周期(源码、class文件、运行时),其参考值见类的定义:java.lang.annotation.RetentionPolicy


@Inherited


指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。


jdk1.8又提供了以下两个元注解


@Native


指定字段是一个常量,其值引用native code。


@Repeatable


注解上可以使用重复注解,即可以在一个地方可以重复使用同一个注解,像spring中的包扫描注解就使用了这个。


JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


所有元注解定义在java.lang.annotation包下面

JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


其中Annotation是注解的基本接口,所有的注解都继承这个接口。


JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


看下@Autowired注解的实现


JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


其实就是继承了Annotation接口。


JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)


了解了jdk对注解的定义,所以想要自定义一个注解就以@interface开始吧。