0Pricing
Kotlin Academy · Lesson

Practical Reflection

Read annotations dynamically.

Annotations Meet Reflection

An annotation with RUNTIME retention can be discovered at runtime via reflection. This combination powers serializers, validators, and dependency injection.

In this lesson we read our own annotations dynamically.

Reading a Class Annotation

Every KClass exposes an annotations list. We can scan it to find a specific annotation by type.

@Retention(AnnotationRetention.RUNTIME)
annotation class Entity(val table: String)

@Entity("users")
class User

fun main() {
    val ann = User::class.annotations
        .filterIsInstance<Entity>()
        .first()
    println(ann.table)
}

All lessons in this course

  1. Using Annotations
  2. Defining Annotations
  3. Reflection Basics
  4. Practical Reflection
← Back to Kotlin Academy