androidengineers.Book a session

Reflection and Runtime Features

Practice: Reflection-Based Utilities

exercise40 minHard

Build an opt-in metadata inspector

Implement a JVM utility that returns sorted names of annotated properties without evaluating their getters. This exercise requires kotlin-reflect and separates metadata discovery from value access.

import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties

@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Inspectable

fun inspectableNames(type: KClass<*>): List<String> =
    type.memberProperties.filter { it.findAnnotation<Inspectable>() != null }
        .map { it.name }.sorted()

Sorting makes the output deterministic because reflection order is not your presentation contract. Property-targeted metadata is inspected through Kotlin properties, not Java fields.

Acceptance checks

Create a model with two annotated properties and an unannotated secret. Verify sorted output, an empty result for an unannotated model, and no getter invocation during discovery. Add a getter that throws to prove discovery remains metadata-only.

Extension: cache results with a bounded lifetime and evaluate whether the workload justifies it. Keep value extraction as a separate, explicitly authorized operation.

Reference: Kotlin reflection

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Practice: Reflection-Based Utilities | Kotlin Core Programming | Android Engineers