androidengineers.Book a session

Reflection and Runtime Features

Runtime Annotation Processing (brief)

article15 minHard

Runtime metadata requires runtime retention

To inspect annotations at runtime, retain them and use a reflection API that matches their target. This JVM example requires kotlin-reflect.

import kotlin.reflect.full.findAnnotation

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Topic(val name: String)

@Topic("Kotlin")
class Basics

fun main() {
    check(Basics::class.findAnnotation<Topic>()?.name == "Kotlin")
}

An annotation on a property, backing field, or getter may be visible through different reflection paths. Choose a use-site target intentionally when interacting with Java frameworks. Code shrinking can affect reflective access, so validate release builds and follow the relevant library's consumer-rule guidance.

Exercise

Inspect one annotated class and one without the annotation. Define whether missing metadata returns null, uses a default, or causes configuration failure.

Check: do not rely on a successful debug build as proof that reflective discovery works after optimization, and do not broadly keep every class as the first response to a missing rule.

Reference: Annotation retention

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Runtime Annotation Processing (brief) | Kotlin Core Programming | Android Engineers