kotlin.reflect provides runtime representations of Kotlin declarations so code can inspect classes, properties, and functions whose details are not known until execution. This supports general-purpose tasks such as object serialization, where code must handle objects of arbitrary types rather than naming every class and property in advance. The API is defined in kotlin.reflect and kotlin.reflect.full, and it can inspect classes written in any JVM language. section 12.2
import kotlin.reflect.full.*
class Person(val name: String, val age: Int)
fun main() {
val person = Person("Alice", 29)
val kClass = person::class #1
println(kClass.simpleName)
// Person
kClass.memberProperties.forEach { println(it.name) }
// age
// name
}
Use obj::class to obtain a KClass at runtime, then enumerate memberProperties to inspect inherited and declared nonextension properties by name. section 12.2.1
KClass is the main entry point. Obtain it with MyClass::class or obj::class; it exposes class names, members, constructors, nested classes, and related declarations. Class names are nullable because an anonymous object has no simpleName or qualifiedName. section 12.2.1
Callable and property references provide progressively more direct access:
- KCallable is the common superinterface for functions and properties. Its call(vararg args) method invokes a function or a property getter, but incorrect argument counts fail at runtime. section 12.2.1
- KFunction values come from references such as ::foo. Typed KFunction0, KFunction1, and similar interfaces can use invoke syntax and preserve compile-time parameter checking. section 12.2.1 section 12.3
- KProperty0 and KProperty1 retrieve values with get; mutable property interfaces add set. A member reference such as Person::age accepts its receiver explicitly. section 12.2.1 section 12.3
Serialize unknown object properties
A serializer can cast obj::class to KClass<Any>, enumerate memberProperties, and call prop.get(obj) for each one. Because enumeration loses the exact property type, each property is treated as KProperty1<Any, *> and produces Any?. The serializer can then emit primitives, strings, collections, or nested objects as JSON values. Passing the object that supplied the properties keeps the reflective receiver correct, despite the missing compile-time check. section 12.2.2 section 12.2
Kotlin classes compile to regular Java bytecode, so java.lang.reflect can also inspect them and Java reflection-based libraries remain compatible. Prefer the Kotlin API when Kotlin concepts such as properties, data classes, and nullable types matter. Add org.jetbrains.kotlin:kotlin-reflect when using it: kotlin-reflect.jar is separate and is not included in new projects by default. section 12.2
