Kotlin 注解 #

一、注解概述 #

注解是代码中的元数据,用于提供代码的额外信息。

二、定义注解 #

2.1 基本语法 #

kotlin
annotation class SimpleAnnotation

2.2 带参数的注解 #

kotlin
annotation class Named(val name: String)

@Named("UserService")
class UserService

2.3 多参数注解 #

kotlin
annotation class Route(
    val path: String,
    val method: String = "GET"
)

@Route("/users", method = "POST")
fun createUser() { }

三、元注解 #

3.1 @Target #

指定注解的目标:

kotlin
@Target(AnnotationTarget.CLASS)
annotation class ClassOnly

@Target(AnnotationTarget.FUNCTION)
annotation class FunctionOnly

@Target(
    AnnotationTarget.CLASS,
    AnnotationTarget.FUNCTION,
    AnnotationTarget.PROPERTY
)
annotation class MultipleTargets

3.2 @Retention #

指定注解的保留策略:

kotlin
@Retention(AnnotationRetention.SOURCE)
annotation class SourceOnly  // 仅源码,编译后丢弃

@Retention(AnnotationRetention.BINARY)
annotation class BinaryOnly  // 编译到 class 文件,但运行时不可见

@Retention(AnnotationRetention.RUNTIME)
annotation class RuntimeVisible  // 运行时可见,可通过反射获取

3.3 @Repeatable #

允许重复使用注解:

kotlin
@Repeatable
annotation class Tag(val value: String)

@Tag("service")
@Tag("api")
class ApiService

3.4 @MustBeDocumented #

注解应包含在文档中:

kotlin
@MustBeDocumented
annotation class Api(val version: String)

四、使用注解 #

4.1 类注解 #

kotlin
@Deprecated("Use NewClass instead")
class OldClass

@Suppress("UNCHECKED_CAST")
fun cast() { }

4.2 函数注解 #

kotlin
@Throws(IOException::class)
fun readFile(path: String) { }

@Synchronized
fun synchronizedMethod() { }

4.3 属性注解 #

kotlin
class User {
    @field:NotNull
    var name: String? = null
    
    @get:NotNull
    val email: String? = null
}

4.4 参数注解 #

kotlin
fun process(@Param("id") id: Int) { }

五、注解目标 #

5.1 目标前缀 #

kotlin
class Example {
    @field:Inject
    var field: String = ""
    
    @get:Inject
    val property: String = ""
    
    @set:Inject
    var mutable: String = ""
    
    @setparam:Inject
    var setterParam: String = ""
    
    @delegate:Inject
    val delegated by lazy { "" }
}

5.2 目标类型 #

目标 说明
file 文件
property 属性(Kotlin)
field 字段(Java)
get getter
set setter
setparam setter 参数
delegate 委托字段
param 构造函数参数
type 类型

六、内置注解 #

6.1 @Deprecated #

kotlin
@Deprecated(
    message = "Use newFunction instead",
    replaceWith = ReplaceWith("newFunction()"),
    level = DeprecationLevel.ERROR
)
fun oldFunction() { }

6.2 @Suppress #

kotlin
@Suppress("UNCHECKED_CAST", "UNUSED_PARAMETER")
fun example() { }

6.3 @JvmStatic #

kotlin
class Utils {
    companion object {
        @JvmStatic
        fun staticMethod() { }
    }
}

6.4 @JvmField #

kotlin
class Constants {
    @JvmField
    val MAX_SIZE = 100
}

6.5 @JvmName #

kotlin
@JvmName("getListOfStrings")
fun List<String>.asStringList(): List<String> = this

七、反射获取注解 #

7.1 类注解 #

kotlin
@RuntimeVisible
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class RuntimeVisible

@RuntimeVisible
class MyClass

fun main() {
    val annotation = MyClass::class.findAnnotation<RuntimeVisible>()
    println(annotation)
}

7.2 函数注解 #

kotlin
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Log

class Service {
    @Log
    fun process() { }
}

fun main() {
    val method = Service::class.memberFunctions.find { it.name == "process" }
    val hasLog = method?.findAnnotation<Log>() != null
}

八、实战示例 #

8.1 路由注解 #

kotlin
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Get(val path: String)

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Post(val path: String)

class UserController {
    @Get("/users")
    fun listUsers() { }
    
    @Post("/users")
    fun createUser() { }
}

8.2 依赖注入注解 #

kotlin
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Component

@Target(AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.RUNTIME)
annotation class Inject

@Component
class UserRepository @Inject constructor() {
    fun findById(id: Int): User? = null
}

8.3 验证注解 #

kotlin
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class NotBlank(val message: String = "不能为空")

@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Min(val value: Int, val message: String = "值太小")

data class User(
    @NotBlank(message = "姓名不能为空")
    val name: String,
    
    @Min(0, message = "年龄不能为负数")
    val age: Int
)

九、最佳实践 #

9.1 选择合适的保留策略 #

kotlin
// 编译时处理 → SOURCE
@Retention(AnnotationRetention.SOURCE)

// 运行时反射 → RUNTIME
@Retention(AnnotationRetention.RUNTIME)

9.2 明确注解目标 #

kotlin
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class Api

9.3 提供默认值 #

kotlin
annotation class Cache(
    val key: String = "",
    val ttl: Long = 3600
)

十、总结 #

注解要点:

概念 说明
定义 annotation class Name
参数 annotation class Name(val value: String)
@Target 注解目标
@Retention 保留策略
@Repeatable 可重复

下一步,让我们学习 反射

最后更新:2026-03-27