注解系统
NovaLang 注解定义与使用
注解系统
NovaLang 支持可扩展的注解系统,可以定义自定义注解并在运行时查询。
定义注解
annotation class Deprecated(val message: String = "")
annotation class Route(val path: String, val method: String = "GET")
annotation class Test
使用注解
@Deprecated("请使用 newMethod()")
fun oldMethod() { /* ... */ }
@Route("/api/users", method = "POST")
fun createUser(name: String) { /* ... */ }
@Test
fun testAddition() {
assert(1 + 1 == 2)
}
注解可以用在函数、类、属性等声明上。
内置注解
@data
自动为类生成 toString()、equals()、hashCode() 和 copy() 方法:
@data
class User(val name: String, val age: Int)
val u = User("Alice", 30)
println(u) // User(name=Alice, age=30)
println(u == User("Alice", 30)) // true
val u2 = u.copy(age = 31) // User(name=Alice, age=31)
@data object
为单例对象自动生成 toString()(返回纯类名),常与 sealed interface 配合表示无数据状态分支:
sealed interface Result {
@data class Success(val value: Int) : Result
@data object Failure : Result // toString() = "Failure"
}
val r: Result = Result.Failure
println(r) // Failure
@builder
自动生成 Builder 模式:
@builder
class Config(val host: String, val port: Int, val debug: Boolean)
val config = Config.builder()
.host("localhost")
.port(8080)
.debug(true)
.build()
运行时查询注解
通过反射 API 查询注解信息:
val info = classOf(User)
// 检查类是否有注解
if (info.hasAnnotation("data")) {
println("这是一个 data class")
}
// 获取注解参数
for (method in info.methods()) {
val route = method.annotation("Route")
if (route != null) {
println("${route.get("method")} ${route.get("path")}")
}
}
自定义注解处理器
可以在 Nova 脚本中注册注解处理器,在注解类/函数被定义时自动执行:
registerAnnotationProcessor("Validate") { target, args ->
// target: 被注解的元素
// args: 注解参数 Map
println("验证: ${target.name}")
}
也可以从 Java 侧注册处理器,用于更深度的集成。