Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Reflection

Kotlin Reflection

Reflection is the ability to inspect program structures such as classes, functions, and properties at runtime and to invoke them dynamically.

Kotlin provides its own set of reflection APIs, used through the kotlin-reflect library; they are more concise than Java reflection and preserve Kotlin-specific information such as nullability and properties.


What is reflection

Normally, the code we write determines at compile time which function to call and which property to access.

Reflection breaks this: the program only learns at runtime which object it is operating on.

For example, a configuration file contains a method name save; after reading it in, the program finds and calls it via reflection, without hardcoding obj.save() in the code.

Common use cases include dependency injection frameworks, serialization libraries, testing tools, and scripting engines.

Business code rarely needs reflection directly, but understanding it helps you read the internal behavior of these frameworks.

The cost of using it

Reflection is powerful but comes at a significant cost; don't overuse it just to "look flexible".

Cost Description
Runtime library size kotlin-reflect Adds about 2.5 MB of dependency to the program
Runtime performance Reflective calls are slower than direct calls, especially lookups by name
Type Safety Method names written as strings mean typos are caught only at runtime
Code obfuscation R8 and ProGuard may rename or remove members accessed via reflection, causing runtime failures
Maintainability The IDE can't navigate or refactor, and class encapsulation is broken

Tip:If logic can be expressed with ordinary code, don't use reflection. Only when "the caller truly doesn't know at compile time what to operate on" is reflection a reasonable choice.


KClass and ::class

Kotlin uses KClass to represent a class's runtime information, obtained via ::class.

KClass is Kotlin's own type; it tells you a class's simple and qualified names, and whether a property is nullable.

Example

package

com.runoob

import

kotlin.reflect.KClass

// Define a sample class

class

Runoob

(

val name

:

String

, var age

:

Int

)

fun main

(

)

{

   

// ClassName::class gives a KClass object

    val kClass

:

KClass

<

Runoob

=

Runoob

::

class

    println

(

"Simple name: ${kClass.simpleName}"

)

    println

(

"Qualified name: ${kClass.qualifiedName}"

)

   

// You can also get a KClass from an instance, of exactly the same type

    val site

=

Runoob

(

"RUNOOB"

,

10

)

    println

(

"Instance's class: ${site::class.simpleName}"

)

    println

(

"Is the same object: ${site::class == Runoob::class}"

)

}

The example produces the following output:



简单名: Runoob

限定名: com.runoob.Runoob

实例的类: Runoob

是同一个对象: true

Note that KClass is a generic type; KClass means it describes the Runoob class.

Generic parameters are written in angle brackets, and KClass itself carries a type parameter so the caller gets the concrete type.

::class.java and Class.kotlin

On the JVM, Kotlin's KClass and Java's Class can be converted into each other.

Call ::class.java to get the Java Class object, then use Class.kotlin to convert back.

Example

package

com.runoob

class

Runoob

(

val name

:

String

)

fun main

(

)

{

   

// KClass -> Class

    val javaClass

:

Class

<

Runoob

=

Runoob

::

class

.

java

    println

(

"Java class name: ${javaClass.name}"

)

   

// Class -> KClass

    val back

=

javaClass.

kotlin

    println

(

"Back to KClass: ${back.simpleName}"

)

}

The example produces the following output:



Java 类名: com.runoob.Runoob

转回 KClass: Runoob

KClass's simpleName, qualifiedName, and java are supported directly by the standard library, with no extra dependency.

More powerful features such as enumerating members, calling functions, and creating instances require kotlin-reflect.


KFunction and function references

When you pass a function as a value, you get a function reference whose type is a subtype of KFunction.

For example, for a function with two parameters the reference type is KFunction2, whose generic parameters are the parameter types followed by the return type.

Example

package

com.runoob

import

kotlin.reflect.KFunction2

// Top-level function

fun add

(

a

:

Int, b

:

Int

)

:

Int

=

a

b

class

Calculator

{

    fun multiply

(

a

:

Int, b

:

Int

)

:

Int

=

a

b

}

fun main

(

)

{

   

// Reference to a top-level function, of type KFunction2

    val f

:

KFunction2

<

Int, Int, Int

=

::

add

    println

(

"Function name: ${f.name}"

)

    println

(

"Number of parameters: ${f.parameters.size}"

)

   

// A direct call is compile-time bound, doesn't go through reflection, and performs close to a normal call

    println

(

"Direct call: ${f(3, 4)}"

)

   

// call is the real reflective call, with arguments passed in order by position

    println

(

"call invocation: ${f.call(3, 4)}"

)

   

// A member function reference requires an instance first

    val calc

=

Calculator

(

)

    val m

=

calc

::

multiply

    println

(

"Member function name: ${m.name}"

)

    println

(

"call invocation: ${m.call(5, 6)}"

)

}

The example produces the following output:



函数名: add

参数个数: 2

直接调用: 7

call 调用: 7

成员函数名: multiply

call 调用: 30

Tip:Function references ::add themselves are not "heavy reflection".f(3, 4) are optimized by the compiler into direct calls; only f.call(3, 4) go through the reflection path. So if you can use invoke don't use call。

If you don't want to remember the parameter order, you can use callBy to pass values by parameter name, taking parameter objects from parameters.

Example

package

com.runoob

fun add

(

a

:

Int, b

:

Int

)

:

Int

=

a

b

fun main

(

)

{

    val f

=

::

add

   

// Pass values by parameter name, order can be shuffled

    val args

=

mapOf

(

f.

parameters

[

1

]

to

4

, f.

parameters

[

0

]

to

3

)

    println

(

"callBy: ${f.callBy(args)}"

)

}

The example produces the following output:



callBy: 7

A function reference has type KFunction, while a normal lambda has type FunctionN; the two can't be directly assigned to each other.


KProperty and property references

Using ClassName::propertyName gives a property reference, of type KProperty1。

where T is the receiver type and R is the property type; if the property is a var, the type becomes KMutableProperty1, which allows writing values.

Example

package

com.runoob

import

kotlin.reflect.KMutableProperty1

import

kotlin.reflect.KProperty1

class

User

(

val name

:

String

, var age

:

Int

)

fun main

(

)

{

    val user

=

User

(

"RUNOOB"

,

10

)

   

// A val property gives KProperty1, read-only

    val nameProp

:

KProperty1

<

User, String

=

User

::

name

    println

(

"Property name: ${nameProp.name}"

)

    println

(

"Read name: ${nameProp.get(user)}"

)

   

// A var property gives KMutableProperty1, readable and writable

    val ageProp

:

KMutableProperty1

<

User, Int

=

User

::

age

    println

(

"Read age: ${ageProp.get(user)}"

)

    ageProp.

set

(

user,

20

)

    println

(

"Age after writing: ${user.age}"

)

}

The example produces the following output:



属性名: name

读取 name: RUNOOB

读取 age: 10

写入后 age: 20

For top-level or object properties the receiver is not an instance, so you get KProperty0, and get() needs no receiver argument.

Example

package

com.runoob

import

kotlin.reflect.KProperty0

// Top-level property

val siteName

:

String

=

"www.runoob.com"

object Config

{

    val version

:

String

=

"Kotlin 2.2"

}

fun main

(

)

{

    val p1

:

KProperty0

<

String

=

::

siteName

    println

(

"${p1.name} = ${p1.get()}"

)

    val p2

:

KProperty0

<

String

=

Config

::

version

    println

(

"${p2.name} = ${p2.get()}"

)

}

The example produces the following output:



siteName = www.runoob.com

version = Kotlin 2.2


Calling functions and reading/writing properties via reflection

In practice, we usually enumerate all members first, then look up the target by name.

The following example lists an object's properties and functions, then finds and calls greet by name.

Example

package

com.runoob

import

kotlin.reflect.KProperty1

import

kotlin.reflect.full.declaredMemberFunctions

import

kotlin.reflect.full.memberProperties

class

Runoob

(

val name

:

String

, var age

:

Int

)

{

    fun greet

(

)

:

String

=

"Welcome to $name"

}

fun main

(

)

{

    val site

=

Runoob

(

"RUNOOB"

,

10

)

    val kClass

=

site

::

class

   

// memberProperties includes superclass properties; Any has no properties, so these are the two

    println

(

"Member properties:"

)

   

for

(

prop in kClass.

memberProperties

.

sortedBy

{

it.

name

}

)

{

       

// Elements of memberProperties carry an out projection, so calling get directly is forbidden; cast to the concrete type first

        @Suppress

(

"UNCHECKED_CAST"

)

        val p

=

prop as KProperty1

<

Runoob,

*>

println

(

"  ${p.name} = ${p.get(site)}"

)

   

}

   

// declaredMemberFunctions only includes functions declared in this class

    println

(

"Functions declared in this class:"

)

   

for

(

func in kClass.

declaredMemberFunctions

.

sortedBy

{

it.

name

}

)

{

        println

(

"  ${func.name}"

)

   

}

   

// Find a function by name and call it

    val greet

=

kClass.

declaredMemberFunctions

.

first

{

it.

name

==

"greet"

}

    println

(

"Call greet(): ${greet.call(site)}"

)

}

The example produces the following output:



Member properties:

  age = 10

  name = RUNOOB

Functions declared in this class:

  greet

调用 greet(): 欢迎来到 RUNOOB

The order of the collection returned by memberProperties isn't guaranteed stable, so the example adds sortedBy.

If you only want members declared by the class itself, use declaredMemberProperties and declaredMemberFunctions, which don't include superclass members.

Note:memberProperties、memberFunctions、call These APIs are all in kotlin-reflect; without the dependency, a KotlinReflectionNotSupportedError。


createInstance for creating instances

KClass.createInstance() can call a no-arg constructor to create an instance, available since Kotlin 1.1.

It requires the class to have a no-arg constructor, or all parameters to have default values, otherwise an exception is thrown.

Example

package

com.runoob

import

kotlin.reflect.full.createInstance

class

Runoob

{

    val siteName

:

String

=

"RUNOOB"

    override fun toString

(

)

:

String

=

"Runoob instance"

}

fun main

(

)

{

    val instance

=

Runoob

::

class

.

createInstance

(

)

    println

(

instance

)

    println

(

instance.

siteName

)

}

The example produces the following output:



Runoob 实例

RUNOOB

If the class needs parameters, use primaryConstructor to get the constructor, then call call.

Example

package

com.runoob

import

kotlin.reflect.full.primaryConstructor

class

Site

(

val name

:

String

, val url

:

String

)

fun main

(

)

{

   

// Get the primary constructor, then pass arguments in order to call

    val ctor

=

Site

::

class

.

primaryConstructor

!!

    val site

=

ctor.

call

(

"RUNOOB"

,

"www.runoob.com"

)

    println

(

"${site.name} -> ${site.url}"

)

}

The example produces the following output:



RUNOOB -> www.runoob.com


The kotlin-reflect dependency

Full reflection functionality requires kotlin-reflect separately; it's not in the standard library.

With Gradle's Kotlin DSL, you can use kotlin("reflect") to let the plugin match the version automatically.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

}

dependencies

{

   

// kotlin("reflect") automatically uses the same version as the Kotlin plugin

    implementation

(

kotlin

(

"reflect"

)

)

   

// You can also hardcode the coordinates; note the version must match the Kotlin compiler

   

// implementation("org.jetbrains.kotlin:kotlin-reflect:2.2.0")

}

With Maven, the coordinates are org.jetbrains.kotlin:kotlin-reflect.

Example

<

dependency

<

groupId

org.

jetbrains

.

kotlin

groupId

   

<

artifactId

kotlin

reflect

artifactId

<

version

2.2.0

version

dependency

Tip:The version of kotlin-reflect must match the Kotlin version used at compile time, otherwise a version-mismatch exception may be thrown at runtime. The online tool play.kotlinlang.org already includes this library, so you can run the examples above directly.


Kotlin reflection vs Java reflection

Kotlin reflection is built on top of Java reflection, but the APIs it exposes fit Kotlin's semantics better.

Comparison Item Kotlin Reflection Java reflection
Entry point obj::class Get KClass obj.javaClass Get Class
Extra dependency Full functionality requires kotlin-reflect Built into the JDK
Function call KFunction.call(...) Method.invoke(...)
Property support Properties are first-class citizens,KProperty readable and writable directly you can only look for getters and setters separately
Nullability KType.isMarkedNullable Can be read Not visible, only via annotations
Type Safety KProperty1 With generics Everything returns Object, requiring casts

Java reflection loads classes by string, e.g. Class.forName("com.runoob.Runoob"), which can't be checked at compile time at all.

Kotlin also keeps this route, but recommends preferring ::class so at least the class name is checked at compile time.

Example

package

com.runoob

import

java.lang.reflect.Method

class

Runoob

(

val name

:

String

)

{

    fun greet

(

)

:

String

=

"Welcome to $name"

}

fun main

(

)

{

   

// Java style: load a class by string; typos are discovered only at runtime

    val clazz

=

Class

.

forName

(

"com.runoob.Runoob"

)

    val ctor

=

clazz.

getConstructor

(

String

::

class

.

java

)

    val instance

=

ctor.

newInstance

(

"RUNOOB"

)

   

// Look up by method name and parameter types

    val method

:

Method

=

clazz.

getMethod

(

"greet"

)

    println

(

method.

invoke

(

instance

)

)

}

The example produces the following output:



欢迎来到 RUNOOB

Kotlin reflection has another capability Java reflection lacks: determining whether a type is nullable.

Example

package

com.runoob

import

kotlin.reflect.full.memberProperties

class

Profile

(

val name

:

String

, val nickname

:

String

?

)

fun main

(

)

{

   

for

(

prop in Profile

::

class

.

memberProperties

.

sortedBy

{

it.

name

}

)

{

        val type

=

prop.

returnType

        println

(

"${prop.name}: ${type}, nullable = ${type.isMarkedNullable}"

)

   

}

}

The example produces the following output:



name: kotlin.String,可空 = false

nickname: kotlin.String?,可空 = true


Common questions

The following questions come up most often when learning reflection.

KotlinReflectionNotSupportedError

It means kotlin-reflect is missing at runtime. Just add implementation(kotlin("reflect")) in build.gradle.kts.

What's the difference between ::class and ::class.java

::class gives Kotlin's KClass, which can read Kotlin semantics such as nullability; ::class.java gives Java's Class, mainly used to call APIs in the Java ecosystem.

Which is faster: function references or reflective calls

Directly invoking a function reference is compile-time bound and performs close to a normal call; only call and name-based lookup go through reflection, with noticeable overhead.

createInstance reports a "no argument constructor" error

The target class has no no-arg constructor. Add default values to parameters, or use primaryConstructor with call to pass arguments.

What happens if reflection modifies a private property

On the JVM you can bypass access checks with isAccessible = true, but this breaks encapsulation and will fail once the module system or obfuscation is enabled, so it's not recommended in production code.