Kotlin在kotlin.annotation包下提供了4个Meta注解(元注解),这4个元注解都用于修饰其他的注解定义。
一、使用@Retention
@Retention只能修饰注解定义,用于指定被修饰的注解可以保留多长时间。@Retention元注解包含一个AnnotationRetention类型的value属性,所以使用@Retention时必须为该value属性指定值。
value属性的值只能是:
- AnnotationRetention.SOURCE:注解只保留在源代码中,编译器直接丢弃这种注解。
- AnnotationRetention.BINARY:编译器将把注解记录在class文件中。当运行该字节码文件时,JVM不可获取注解信息。
- AnnotationRetention.RUNTIME:编译器将把注解记录在class文件中。当运行该字节码文件时,JVM也可获取注解信息,程序可以通过反射获取该注解信息。
二、使用@Target
@Target只能修饰注解定义,用于指定被修饰的注解能修饰那些程序单元。
@Target元注解包含一个类型为AnnotationTarget数组的allowedTargets属性,该属性的值只能是如下几个值组成的数组:
- AnnotationTarget.CLASS:指定该策略的注解只能修饰类。
- AnnotationTarget.ANNOTATION_CLASS:指定该策略的注解只能修饰注解。
- AnnotationTarget.TYPE_PARAMETER:指定该策略的注解只能修饰泛型形参。
- AnnotationTarget.PROPERTY:指定该策略的注解只能修饰属性。
- AnnotationTarget.FIELD:指定该策略的注解只能修饰字段。
- AnnotationTarget.LOCAL_VARIABLE:指定该策略的注解只能修饰局部变量。
- AnnotationTarget.VALUE_PARAMETER:指定该策略的注解只能修饰函数或构造器的形参。
- AnnotationTarget.CONSTRUCTOR:指定该策略的注解只能修饰构造器。
- AnnotationTarget.FUNCTION:指定该策略的注解只能修饰函数和方法。
- AnnotationTarget.PROPERTY_GETTER:指定该策略的注解只能修饰属性的getter方法。
- AnnotationTarget.PROPERTY_SETTER:指定该策略的注解只能修饰属性的setter方法。
- AnnotationTarget.TYPE:指定该策略的注解只能修饰类型。
- AnnotationTarget.EXPRESSION:指定该策略的注解只能修饰各种表达式。
- AnnotationTarget.FILE:指定该策略的注解只能修饰文件。
- AnnotationTarget.TYPEALIAS:指定该策略的注解只能修饰类型别名。
三、使用@MustBeDocumented
使用@MustBeDocumented元注解修饰的注解将被文档工具提取到API文档中,如果定义注解类时使用了@MustBeDocumented修饰,则所有使用该元注解修饰的程序元素的API文档中将会包含该注解说明。
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
@MustBeDocumented
annotation class Testable
四、使用@Repeatable标记可重复注解
Kotlin允许使用多个相同的注解来修饰同一个程序单元,这种注解称为可重复注解。
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)
@Repeatable//指定该注解是可重复注解
annotation class Flag(val name:String="你是谁",val age:Int)
在Java 8之前,可重复注解的@Retention策略只能指定为AnnotationRetention.SOURCE