- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 168字
- 2021-06-24 19:15:25
Annotations
Annotations are a way to attach meta info to your code (such as documentation, configuration, and others).
Let's look at the following example code:
annotation class Tasty
An annotation itself can be annotated to modify its behavior:
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Tasty
In this case, the Tasty annotation can be set on classes, interfaces, and objects, and it can be queried at runtime.
For a complete list of options, check the Kotlin documentation.
Annotations can have parameters with one limitation, they can't be nullable:
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Tasty(val tasty:Boolean = true)
@Tasty(false)
object ElectricOven : Oven {
override fun process(product: Bakeable) {
println(product.bake())
}
}
@Tasty
class CinnamonRoll : Roll("Cinnamon")
@Tasty
interface Fried {
fun fry(): String
}
To query annotation values at runtime, we must use the reflection API (kotlin-reflect.jar must be in your classpath):
fun main(args: Array<String>) {
val annotations: List<Annotation> = ElectricOven::class.annotations
for (annotation in annotations) {
when (annotation) {
is Tasty -> println("Is it tasty? ${annotation.tasty}")
else -> println(annotation)
}
}
}
推薦閱讀
- Learning Selenium Testing Tools with Python
- Cocos2d-x游戲開發:手把手教你Lua語言的編程方法
- AngularJS Web Application Development Blueprints
- iOS應用逆向工程(第2版)
- C語言程序設計教程
- Keras深度學習實戰
- Yii Project Blueprints
- Swift 4 Protocol-Oriented Programming(Third Edition)
- Unity 3D/2D移動開發實戰教程
- Java 從入門到項目實踐(超值版)
- C#面向對象程序設計(第2版)
- Hacking Android
- RESTful Web API Design with Node.js
- HTML5程序開發范例寶典
- 信息學競賽寶典:基礎算法