Reflection-Based Validation and Mapping
Build a simple validator or object mapper using annotation-driven reflection.
What This Pattern Solves
Reflection-based validation reads annotations from a class's properties at runtime and applies validation rules automatically — no manual checks per field. The same technique powers ORM mappers that convert between objects and database rows.
The Validate Annotation
Define a runtime-retained annotation targeting properties:
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class Validate(
val minLength: Int = 0,
val maxLength: Int = Int.MAX_VALUE,
val pattern: String = ""
)All lessons in this course
- Kotlin Reflection: KClass, KFunction, KProperty
- Creating and Targeting Custom Annotations
- Reading Annotations at Runtime
- Reflection-Based Validation and Mapping