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