7.8 注解类
Kotlin 的注解与 Java 的注解完全兼容。
7.8.1 声明注解
annotation class 注解名
代码示例:
@Target(AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.EXPRESSION,
AnnotationTarget.FIELD,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.TYPE,
AnnotationTarget.TYPEALIAS,
AnnotationTarget.TYPE_PARAMETER,
AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
@Repeatable
annotation class MagicClass
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
@Repeatable
annotation class MagicFunction
@Target(AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
@Repeatable
annotation class MagicConstructor
在上面的代码中,我们通过向注解类添加元注解(meta-annotation)的方法来指定其他属性:
- @Target :指定这个注解可被用于哪些元素(类, 函数, 属性, 表达式, 等等.);
- @Retention :指定这个注解的信息是否被保存到编译后的 class 文件中, 以及在运行时是否可以通过反
射访问到它; - @Repeatable:允许在单个元素上多次使用同一个注解;
- @MustBeDocumented : 表示这个注解是公开 API 的一部分, 在自动产生的 API 文档的类或者函数签名中, 应该包含这个注解的信息。
这几个注解定义在kotlin/annotation/Annotations.kt
类中。
7.8.2 使用注解
注解可以用在类、函数、参数、变量(成员变量、局部变量)、表达式、类型上等。这个由该注解的元注解@Target定义。
@MagicClass class Foo @MagicConstructor constructor() {
constructor(index: Int) : this() {
this.index = index
}
@MagicClass var index: Int = 0
@MagicFunction fun magic(@MagicClass name: String) {
}
}
注解在主构造器上,主构造器必须加上关键字 “constructor”
@MagicClass class Foo @MagicConstructor constructor() {
...
}
当前内容版权归 JackChan1999 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 JackChan1999 .