官术网_书友最值得收藏!

  • 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)
}
}
}
主站蜘蛛池模板: 枣庄市| 浦城县| 绥江县| 宜昌市| 特克斯县| 融水| 教育| 洪雅县| 壤塘县| 乐业县| 南陵县| 霸州市| 丹凤县| 扎兰屯市| 广丰县| 资兴市| 佛坪县| 铜陵市| 云阳县| 阳朔县| 佛山市| 乐山市| 桐城市| 滦平县| 岑溪市| 玉环县| 丹阳市| 天全县| 徐水县| 镇雄县| 福泉市| 洪湖市| 布拖县| 白朗县| 简阳市| 临沂市| 巴塘县| 高陵县| 精河县| 曲靖市| 南阳市|