liveBook · Manning

Kotlin.reflect

As explained in Kotlin in Action, 2E

The Kotlin reflection API provides runtime and compile-time facilities for inspecting Kotlin declarations, types, and callable members.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains KClass, callable and property interfaces, invocation, and reflective serialization, while deferring annotation-based serialization customization.
Examples
Demonstrates Person property enumeration, calling ::foo, invoking sum, mutating counter, and serializing an arbitrary object to JSON.
What it assumes
Assumes familiarity with callable references and object expressions while showing runtime class, function, and property access directly.
What you can do after
Build it from scratch: enumerate object properties and serialize their dynamically retrieved values to JSON.
How it connects
Connects KClass, KCallable, KFunction, KProperty, JSON serialization, annotations, and Java reflection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.