Practical Reflection
Read annotations dynamically.
Practical Reflection is a free Kotlin Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)
}findAnnotation Helper
The findAnnotation extension is cleaner than filtering manually. It returns the annotation or null.
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Entity(val table: String)
@Entity("orders")
class Order
fun main() {
val ann = Order::class.findAnnotation<Entity>()
println(ann?.table)
}Annotations on Properties
Properties carry their own annotations. Iterate memberProperties and inspect each property's annotations.
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Column(val name: String)
class Product(@Column("product_id") val id: Int, val title: String)
fun main() {
Product::class.memberProperties.forEach { prop ->
val col = prop.findAnnotation<Column>()
if (col != null) println(prop.name + " -> " + col.name)
}
}Building a Mini Serializer
Combine property reading with annotations to generate output. Here we map each property to a key=value string using the column name when present.
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Column(val name: String)
class Item(@Column("item_id") val id: Int, val name: String)
fun main() {
val item = Item(7, "Book")
val parts = Item::class.memberProperties.map { p ->
val key = p.findAnnotation<Column>()?.name ?: p.name
key + "=" + p.getter.call(item)
}
println(parts.joinToString(", "))
}Skipping With a Marker
A marker annotation can flag properties to ignore. We test for its presence with hasAnnotation.
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.hasAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Transient2
class Account(val id: Int, @Transient2 val secret: String)
fun main() {
Account::class.memberProperties
.filterNot { it.hasAnnotation<Transient2>() }
.forEach { println(it.name) }
}Reading Annotation Arguments
Once you have the annotation instance, its parameters are plain properties. Read them like any field.
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Validated(val min: Int, val max: Int)
@Validated(min = 1, max = 100)
class Quantity
fun main() {
val v = Quantity::class.findAnnotation<Validated>()!!
println("range " + v.min + ".." + v.max)
}Annotations on Functions
Functions can also be annotated and inspected. Frameworks use this to find handlers, like test runners locating test methods.
import kotlin.reflect.full.memberFunctions
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Route(val path: String)
class Api {
@Route("/home")
fun home() = "home page"
}
fun main() {
Api::class.memberFunctions.forEach { f ->
f.findAnnotation<Route>()?.let { println(f.name + " @ " + it.path) }
}
}Driving Behavior
Read the route annotation and actually dispatch a call. This is the essence of how routing frameworks work.
import kotlin.reflect.full.memberFunctions
import kotlin.reflect.full.findAnnotation
@Retention(AnnotationRetention.RUNTIME)
annotation class Route(val path: String)
class Api {
@Route("/ping")
fun ping() = "pong"
}
fun main() {
val api = Api()
val target = "/ping"
Api::class.memberFunctions.forEach { f ->
if (f.findAnnotation<Route>()?.path == target) {
println(f.call(api))
}
}
}Real-World Uses
Annotation-driven reflection underpins many libraries:
- JSON serialization mapping fields to keys
- Validation enforcing constraints
- Routing matching paths to handlers
- Dependency injection wiring components
Keep It Targeted
Reflection is best confined to setup and framework code that runs once or rarely. Cache the results when you can. For per-request hot paths, prefer compile-time processing.
Quick Check
Test your understanding of practical reflection.
Recap
You combined annotations and reflection to:
- Find class, property, and function annotations
- Read annotation arguments at runtime
- Build a mini serializer and route dispatcher
- Skip fields with marker annotations
This is how real frameworks are built.
Frequently asked questions
Is the “Practical Reflection” lesson free?
Yes — the full text of “Practical Reflection” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Practical Reflection”?
Read annotations dynamically. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Practical Reflection” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Using Annotations
- Defining Annotations
- Reflection Basics
- Practical Reflection