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

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)
}
}
}
主站蜘蛛池模板: 平远县| 色达县| 广丰县| 长泰县| 石首市| 新和县| 清流县| 容城县| 方山县| 天全县| 馆陶县| 且末县| 湖南省| 修武县| 莒南县| 远安县| 邵东县| 康定县| 泸定县| 石台县| 阿尔山市| 呼伦贝尔市| 浮梁县| 五大连池市| 专栏| 井研县| 涿鹿县| 通山县| 四川省| 和平县| 丰顺县| 辛集市| 义乌市| 柳林县| 神池县| 屯昌县| 泰和县| 五原县| 菏泽市| 宿州市| 土默特左旗|