Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 134 ยท Idiomatic Kotlin

Reflection Overview

Understand Kotlin reflection: KClass and ::class, callable and property references, what needs kotlin-reflect, Java reflection as a fallback, dynamic proxies and the cost and risks.

Reflection is a program looking at itself: asking an object what class it has, which functions and properties that class declares, and then reading a property or calling a function by name. Most code never needs it, because normal code knows its types at compile time. But frameworks live on it: JSON libraries find the properties of your class, dependency injection builds objects by reading constructors, test runners find functions by annotation, and serialization, ORMs and mocking all depend on looking at types at run time.

Kotlin has three layers of reflection, and knowing which layer you are in avoids a lot of confusion. This lesson tours them: the cheap built-in features (::class, callable references) that always work, the Java reflection API that works on every JVM, and the full Kotlin reflection library kotlin-reflect, which is a separate dependency. kotlin-reflect is not available in the runner on this site, so the lesson shows that part as read-only code and demonstrates exactly what fails. It builds on Annotations and Type Erasure and reified.

Layer 1: class references with ::class

SomeType::class gives a KClass object (a class reference), and value::class gives the class of an object at run time. Without any extra library, a KClass can tell you its names and let you compare classes:

Kotlin KClass basics without kotlin-reflect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two things to notice. value::class uses the object's real class, not its declared type, which makes it the tool for checking "what is this really?". And the names you see for built-in types are the Kotlin ones (Int, String), even though on the JVM the underlying class is java.lang.Integer. A KClass is Kotlin's view of a class; value::class.java gives the Java Class object, which you need for Java APIs. The next example prints a KClass directly. Without kotlin-reflect, its toString is class java.lang.String (Kotlin reflection is not available), a harmless note that you can ignore; the other lines show the Java side.

Kotlin From KClass to the Java Class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note the difference between Int::class.java (the primitive int) and Int::class.javaObjectType (the box). It matters when you search for a Java method by parameter types.

Layer 1b: callable references

A callable reference points to a function or property without calling it: ::println, String::length, obj::method, Point::x. They always work, are resolved at compile time and are covered in Higher-Order Functions. The reference object also carries a small amount of information that you can read at run time, such as the name:

Kotlin Function and property references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This is the sweet spot of Kotlin reflection that needs no library: you can pass a property as a value (Person::name) and use its name, get and set. Sorting with sortedBy(Person::name), mapping with map(Person::age) and building validation rules from property references all rely on this. Its limit: you can only reference what you name in source code. You cannot ask a class "which properties do you have?" without the next layer.

What needs kotlin-reflect

The question "list all properties, functions or constructors of a class" is answered by KClass.memberProperties, KClass.members, KClass.declaredFunctions, primaryConstructor, createInstance() and similar. They live in the kotlin-reflect library, a separate artifact of roughly three megabytes that you add as a dependency. Typical use in a project with a build tool:

Kotlin
// read-only example: requires the kotlin-reflect dependency (not available in the runner)
import kotlin.reflect.full.memberProperties

data class Settings(val host: String, val port: Int)

fun main() {
    val s = Settings("example.test", 8080)
    for (property in Settings::class.memberProperties) {
        println("${property.name} = ${property.get(s)}")
    }
}

Running this with the dependency prints each property name with its value. On this site's runner the library is missing. Here is the real behavior:

Kotlin kotlin-reflect is not available (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

KClass.members is declared in the standard library, so the code compiles, and start is printed. The first call that needs the full reflection engine then throws Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath. The same happens for isData, isSealed and friends. The extension properties from kotlin.reflect.full, such as memberProperties, are worse: that package is part of the library itself, so import kotlin.reflect.full.memberProperties does not even compile here (error: unresolved reference 'full'). This is a common surprise in real projects too: an app that compiles but dies in production because the dependency was only on the test classpath. Fortunately Java reflection fills most gaps.

Layer 2: Java reflection, always available

Kotlin classes are JVM classes, so the whole java.lang.reflect API works on them. You get fields, methods, constructors, modifiers and annotations, though you see them as the compiler generated them: a Kotlin property appears as a private field plus getter and setter methods.

Kotlin Inspecting a class with Java reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can see the properties turned into three fields (pages and title are private final, rating is only private because it is a var), the methods getTitle, getPages, getRating, setRating, the data class members copy, component1 to component3, equals, hashCode and toString, and two constructors: the real one and a synthetic one with an extra int and a DefaultConstructorMarker, which Kotlin uses to support default argument values. Reading names of the Kotlin concepts (nullability, data class, default values) is what Java reflection cannot do directly, which is the reason kotlin-reflect exists.

Creating objects and calling methods by name

With a Class object you can create instances and call methods without a compile-time reference. Frameworks do this when a class name comes from a configuration file:

Kotlin Create an object and call a method by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice what the example just did: it called a private function and replaced the value of a private val. Reflection ignores visibility once you call isAccessible = true. That is powerful for test tools and frameworks and terrible for application code: it breaks encapsulation and fails under the Java module system or a security manager. On Java 25 (used here), reflective access into JDK internals is strictly controlled, though your own classes remain open.

Dynamic proxies: an object made at run time

java.lang.reflect.Proxy creates an object that implements an interface at run time and sends every call to a handler. It is the basis for many mocking and remote-call libraries, and you need only the standard JDK:

Kotlin A logging proxy for an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The proxy printed the call, the real implementation ran, and the result was printed on the way back, with no change to RealCalculator. Note that a proxy works only for interfaces; to wrap classes, tools such as ByteBuddy generate subclasses, which is a different technique.

Where Kotlin gets its metadata

Since Java reflection cannot show Kotlin features, Kotlin stores extra information in every class it compiles: the annotation @kotlin.Metadata, which you saw in the annotations lesson. kotlin-reflect decodes it. That data is what knows that Book.title is a non-null String, which constructor is primary, which class is a data class or sealed, and the default values of parameters. KClass.isData, isSealed, sealedSubclasses, nestedClasses and KProperty.returnType need it too and therefore need the library.

Kotlin
// read-only example: requires kotlin-reflect
import kotlin.reflect.full.*

sealed interface Shape
data class Circle(val r: Double) : Shape
data class Square(val side: Double) : Shape

fun main() {
    println(Shape::class.isSealed)                          // true
    println(Shape::class.sealedSubclasses.map { it.simpleName })   // Circle and Square (order not guaranteed)
    println(Circle::class.primaryConstructor?.parameters?.map { it.name })   // [r]
    println(Circle::class.memberProperties.first().returnType)      // kotlin.Double
}

The comments describe what the code prints when the library is present (this is read-only, so it was not run here). Try to avoid needing this: in most designs, a when over a sealed type or an explicit list of subclasses replaces sealedSubclasses with something the compiler checks.

Costs and risks

  • Speed. A reflective call is slower than a direct call, often by an order of magnitude, because the JVM cannot inline it and must check access and boxing. Cache Method and Field objects instead of looking them up for each call. For occasional use, nobody will notice.
  • No compile-time safety. Names are strings. Renaming a property breaks reflective code silently until it runs. Prefer property references (Person::name), which are checked by the compiler and survive refactoring.
  • Encapsulation. isAccessible = true ignores private. Do not use it in application code.
  • Shrinkers and obfuscators. Android's R8 and ProGuard rename or delete code they think is unused; reflective code needs explicit keep rules.
  • Startup and size. kotlin-reflect adds about three megabytes and some start-up time, which is why many libraries (kotlinx.serialization, Dagger, Room) generate code at compile time instead of reflecting at run time.
  • Prefer inline functions with reified type parameters, sealed types, generics and plain function references over reflection. Reach for it when writing a framework, a generic tool or a test helper.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between Animal::class and animal::class?

    Type::class names a class at compile time. value::class is the actual class of the object, so for an Animal variable holding a Dog it is Dog.
  2. 2. Which of these works without the kotlin-reflect library?

    Property references are resolved by the compiler and can be read and called. Listing members, sealed subclasses or constructors needs the full reflection library.
  3. 3. What happens when code calls Settings::class.memberProperties and kotlin-reflect is missing?

    The API is declared in the standard library but the implementation lives in kotlin-reflect, so the missing dependency shows up only when the call runs.
  4. 4. Which tool lets you create an object that implements an interface at run time?

    Proxy.newProxyInstance builds an object that forwards every interface call to an InvocationHandler. It works only for interfaces.
  5. 5. Why prefer Person::name over the string "name" when you can?

    A reference is a typed, compile-time-checked link. A string name is only discovered to be wrong when the code runs.

Summary

  • Type::class and value::class give a KClass; simpleName, qualifiedName, equality and .java work without extra libraries.
  • Function and property references (::f, Person::name) always work, can be called, and expose name, get and set.
  • Listing members, sealed subclasses, constructors or Kotlin types needs kotlin-reflect, a separate dependency that is not available in this runner.
  • Java reflection (getDeclaredFields, getMethod, newInstance, Proxy) works everywhere but shows the compiled form of Kotlin code.
  • Reflection is slow-ish, unchecked by the compiler and able to bypass private; cache lookups and prefer references, reified generics and sealed types.
  • Use reflection for frameworks, tools and tests, rarely for application logic.

Next: Packages and Imports