liveBook · Manning

Reflection

As explained in Kotlin in Action, 2E

Reflection is a programming capability for inspecting or interacting with program types, members, values, or metadata dynamically at runtime.

Reflection lets a program inspect classes, properties, methods, types, annotations, and constructors at run time rather than naming every declaration in source code. It is useful when code must handle arbitrary object types whose structure is not known until execution, such as a JSON serializer or deserializer. section 12.2 section 12.0

Inspect properties dynamically

A serializer can obtain an object's runtime class, enumerate its member properties, ignore properties marked with `JsonExclude`, and read each remaining value. Annotation lookup can also replace a Kotlin property name with a JSON-specific name before writing it. section 12.2.3

Listing 12.2 Serializing an object with property filtering
private fun StringBuilder.serializeObject(obj: Any) {
   (obj::class as KClass<Any>)
       .memberProperties
       .filter { it.findAnnotation<JsonExclude>() == null }
       .joinToStringBuilder(this, prefix = "{", postfix = "}") {
           serializeProperty(it, obj)
       }
}

This implementation shows the central reflective flow: obtain `obj::class`, inspect `memberProperties`, filter by annotation, and serialize each property without knowing the object's class beforehand. section 12.2.3

Kotlin reflection is provided by `kotlin.reflect` and `kotlin.reflect.full`. It models Kotlin-specific constructs including data classes, properties, and nullable types, while also working with classes from any JVM language. Java reflection through `java.lang.reflect` remains available because Kotlin compiles to regular Java bytecode; Java libraries that rely on reflection can therefore work with Kotlin classes. section 12.2

Reflection can drive both directions of JSON conversion:

  • For serialization, inspect properties, retrieve values with `KProperty1.get`, and use annotations to exclude, rename, or apply a custom value serializer. section 12.2.3
  • For deserialization, retain the target type at run time, match JSON names to constructor parameters, convert values according to `KParameter.type`, and construct the result. section 12.2.4 section 12.2.5
  • Use `KCallable.callBy` to invoke a constructor from a parameter-to-value map. Missing optional parameters can then receive their default values, and JSON fields need not arrive in constructor order. section 12.2.5
  • Cache constructor parameters, annotation data, and serializers by `KClass` when repeatedly processing objects of the same type. section 12.2.5

Constructing nested objects from JSON

`deserialize<Book>(json)` can produce a `Book` containing an `Author`. Parsing first turns JSON text into tokens and semantic structures; the deserialization component then uses reflection to create the final Kotlin objects. section 12.2.4

Reflection moves some checks from compile time to run time. A value passed through `callBy` must match its constructor parameter type or an `IllegalArgumentException` can result, so deserializers need explicit conversion for values such as numeric types. Kotlin reflection is distributed separately as `kotlin-reflect.jar`; projects using it must add `org.jetbrains.kotlin:kotlin-reflect` as a dependency. section 12.2.5 section 12.2

How Kotlin in Action, 2E covers it

How deep it goes
Works through property inspection, annotation lookup, constructor invocation, type conversion, and cached metadata for deserialization.
Examples
Demonstrates Person property filtering and renaming, custom Date serialization, and nested Book and Author deserialization.
What it assumes
Builds from ordinary class and function references toward runtime access to declarations whose names are not known in advance.
What you can do after
Build it from scratch by inspecting properties, mapping JSON fields to constructor parameters, converting values, and invoking constructors reflectively.
How it connects
Connects reflection with annotations, JSON serialization, JSON deserialization, reified type parameters, KClass, KProperty, KParameter, and KCallable.

Also explained in

Compare how 13 books explain 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.