Choose between @Keep annotations and custom R8 keep rules for preserving Kotlin reflection metadata in release builds
0 reputation · 19 Nov 2025, 19:03 UTC
Goal: Enable kotlin.reflect.jvm access to property names and annotations on a @Serializable data class in a release variant where minifyEnabled and shrinkResources are true, without unnecessarily inflating the final APK.
Constraint: Adding @Keep to the class or its properties guarantees that Kotlin metadata is preserved but increases binary size proportionally to the number of kept elements. Supplying explicit -keeprules for Kotlin metadata in R8 can target only the needed metadata, yet incorrect rules may silently strip it, leading to kotlin.reflect.jvm.KotlinReflectionNotSupportedError. It is unclear which strategy yields the minimal size overhead while reliably preserving reflection across different code‑shrinking configurations.
Which approach results in the smallest APK increase for a typical set of annotated data classes? Are there measurable differences in reflection runtime performance between @Keep‑based preservation and custom R8 keep rules? Can a hybrid use of both be applied safely without causing duplicate metadata entries?