0Pricing
Kotlin Academy · Lesson

Reading Annotations at Runtime

Retrieve annotation instances from declarations using Kotlin reflection.

Prerequisites

To read annotations at runtime you need: (1) the annotation declared with @Retention(RUNTIME), (2) the kotlin-reflect dependency on the classpath, and (3) a KClass, KFunction, or KProperty reference to the annotated element.

Reading Annotations from a KClass

Call annotations on a KClass to get all annotations on that class, or use findAnnotation() for a specific type:

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

@Table(name = "users")
class UserEntity

val ann = UserEntity::class.findAnnotation<Table>()
println(ann?.name)  // "users"

All lessons in this course

  1. Kotlin Reflection: KClass, KFunction, KProperty
  2. Creating and Targeting Custom Annotations
  3. Reading Annotations at Runtime
  4. Reflection-Based Validation and Mapping
← Back to Kotlin Academy