- 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)
}
}
}
推薦閱讀
- Redis入門指南(第3版)
- Mastering RabbitMQ
- Visual Basic 6.0程序設計計算機組裝與維修
- Ext JS Data-driven Application Design
- Python從菜鳥到高手(第2版)
- TestNG Beginner's Guide
- Responsive Web Design with HTML5 and CSS3
- INSTANT Weka How-to
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- 創意UI:Photoshop玩轉APP設計
- Qt 4開發實踐
- 從零開始學Selenium自動化測試:基于Python:視頻教學版
- Selenium WebDriver Practical Guide
- Learning Cocos2d-JS Game Development
- Microsoft Dynamics GP 2013 Cookbook