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
- Using Annotations
- Defining Annotations
- Reflection Basics
- Practical Reflection