Kotlin 注解

文章目录

定义

注解使用annotation关键字定义,且只能用于普通类,该类被称为注释类。可以使用@注释类为某个变量、函数、类、接口等注释。与我们写的代码注释类似,注释类可以指明被标注类的状态、作用等等(注解一般是在代码检查、编译时使用,非专业人士了解一下即可,会用就行)。

kt 复制代码
// 定义注解
annotation class MyAnnotation()


// 标注变量(无论写在同一行还是换行都行)
@MyAnnotation val name = "Kotlin"

// 标注函数
@MyAnnotation
fun getName() = name


// 标注 lambda 函数
val myLambda = @MyAnnotation {
    
}


// 标注主构造函数(需要给出 constructor 关键字)
class MyClazz @MyAnnotation constructor()


// 标注 getter
val kVersion
    @MyAnnotation
    get() = "2.0.0"


// 标注类
@MyAnnotation
class MyClass


// 标注接口
@MyAnnotation
interface MyInterface

注解类中**不能声明成员(变量或方法),但可以在构造函数处声明成员变量。

如果注解类构造函数有参数,在标注时可以传入:

kt 复制代码
annotation class MyAnnotation(val name: String)


@MyAnnotation("MyClass")
class MyClass

注解类的注解

可以对注解类进行注解标记,以满足我们的需求(以下这些注解只能用于标注注解类)。

  • @Target用于指定可被注解类标记的类型,可以传入0个(此时无法标注)或多个枚举类AnnotationTarget的值。

    kt 复制代码
    // 指定只能对类别名 typealias 使用
    @Target(AnnotationTarget.TYPEALIAS)
    annotation class MyAnnotation()
    
    
    @MyAnnotation typealias Anything = Any
    
    
    // @MyAnnotation 此时不能标记 MyClass
    class MyClass
  • @Retention指定该注解是否存在于编译后的 class 文件中和是否在运行时反射可见,默认都为true(非专业人士表示不懂)。

  • @Repeatable指定该注解可以多次用于同一目标。默认为false

  • @MustBeDocumented指明该注解是公共 API(public API)并且在生成 API(generated API)的类或方法标签名中应该说明(非专业人士)。

标注目标声明

当我们标注时,可以声明被标注的目标:

kt 复制代码
annotation class MyAnnotation


// 标注 setter
@set:MyAnnotation
var name = "Kotlin"

可以使用的目标声明有:

  • file
  • property
  • field
  • get
  • set
  • receiver
  • param
  • setparam
  • delegate
相关推荐
starrycode88817 小时前
【每日一个知识点】Kotlin基础语法核心学习笔记
笔记·学习·kotlin
alexhilton1 天前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack
用户69371750013841 天前
29.Kotlin 类型系统:智能转换:类型检查 (is) 与类型转换 (as)
android·后端·kotlin
用户69371750013841 天前
30. Kotlin 扩展:为“老类”添“新衣”:扩展函数与扩展属性
android·后端·kotlin
ForteScarlet1 天前
如何解决 Kotlin/Native 在 Windows 下 main 函数的 args 乱码?
开发语言·windows·kotlin
starrycode8882 天前
【每日一个知识点】Kotlin开发基础知识
ui·kotlin
愤怒的代码2 天前
深入理解 IdleHandler:从启动优化到内存管理
android·架构·kotlin
Kapaseker2 天前
一万四千字重温 Android 四大组件
android·kotlin
我爱烤冷面2 天前
kotlin项目实现Java doc的方案:使用Dokka
java·开发语言·kotlin·dokka
jian110582 天前
android java转kotlin,kotlin转java
android·java·kotlin