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中的包掃描注解就使用了這個。
?
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan {所有元注解定義在java.lang.annotation包下面
?
其中Annotation是注解的基本接口,所有的注解都繼承這個接口。
?
看下@Autowired注解的實現
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autowired {/*** Declares whether the annotated dependency is required.* <p>Defaults to {@code true}.*/boolean required() default true;}其實就是繼承了Annotation接口。
?
了解了jdk對注解的定義,所以想要自定義一個注解就以@interface開始吧。
總結
以上是生活随笔為你收集整理的JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 这 30 个常用的 Maven 命令你必
- 下一篇: Java 必看的 Spring 知识汇总