Instead of using Java fields and Java reflection code, you can also use Kotlin properties and Kotlin reflection classes:

class Reflector {
    val Foo = 1;

    fun printFields() {
        this::class.memberProperties.forEach {
            if (it.visibility == KVisibility.PUBLIC) {
                println(it.name)
                println(it.getter.call(this))
            }
        }
    }
}
Answer from BladeCoder on Stack Overflow
Discussions

jvm - kotlin reflection get list of fields - Stack Overflow
For the secret backing fields behind a property, use Java reflection at your own risk. ... Sign up to request clarification or add additional context in comments. ... Where MyClass is the class of your choice. In order to use this you need to have kotlin-reflect included in your gradle build ... More on stackoverflow.com
🌐 stackoverflow.com
java - Kotlin reflection - getting all field names of a Class - Stack Overflow
and is it possible to create an MyClass object, and set these declaredFields (using the Java reflection) with the Field.name? 2016-09-20T09:31:10.747Z+00:00 ... In case java class has a field is public static final String, can I get its string value? 2018-03-17T03:19:25.74Z+00:00 ... import kotlin.... More on stackoverflow.com
🌐 stackoverflow.com
(Reflections) Get list of fields?
Did you ask on Stack Overflow ? I know the JetBrains Kotlin team regular post answers there. More on reddit.com
🌐 r/Kotlin
6
4
February 7, 2015
How to change a kotlin private val using reflection? - Stack Overflow
Exception in thread "main" ...t.jvm.internal.KProperty1Impl and kotlin.reflect.KMutableProperty are in unnamed module of loader 'app') at MainKt.main(main.kt:107) at MainKt.main(main.kt) since no setter code is generated for val fields, and thus the info property will have ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
DevTut
devtut.github.io › kotlin › reflection.html
Kotlin - Reflection
Another approach is to make private properties accessible using reflection: example::class.memberProperties.forEach { member -> member.isAccessible = true println("${member.name} -> ${member.get(example)}") } As an example we want to set all string properties of a sample class · class TestClass { val readOnlyProperty: String get() = "Read only!" var readWriteString = "asd" var readWriteInt = 23 var readWriteBackedStringProperty: String = "" get() = field + '5' set(value) { field = value + '5' } var readWriteBackedIntProperty: Int = 0 get() = field + 1 set(value) { field = value - 1 } var dele
🌐
Baeldung
baeldung.com › home › kotlin › kotlin classes and objects › reflection with kotlin
Reflection with Kotlin | Baeldung on Kotlin
March 19, 2024 - Note that the concept of Properties also works in any non-Kotlin code. These are identified by fields that follow the JavaBeans conventions regarding getter and setter methods.
🌐
Rip Tutorial
riptutorial.com › setting values of all properties of a class
Kotlin Tutorial => Setting values of all properties of a class
class TestClass { val readOnlyProperty: String get() = "Read only!" var readWriteString = "asd" var readWriteInt = 23 var readWriteBackedStringProperty: String = "" get() = field + '5' set(value) { field = value + '5' } var readWriteBackedIntProperty: Int = 0 get() = field + 1 set(value) { field = value - 1 } var delegatedProperty: Int by TestDelegate() private var privateProperty = "This should be private" private class TestDelegate { private var backingField = 3 operator fun getValue(thisRef: Any?, prop: KProperty<*>): Int { return backingField } operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: Int) { backingField += value } } }
🌐
GitHub
gist.github.com › jaredrummler › c5e7c212ec54a149b7e69da3967e4d4b
Java reflection made easy using Kotlin · GitHub
Java reflection made easy using Kotlin. GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
🌐
Kotlin
kotlinlang.org › docs › reflection.html
Reflection | Kotlin Documentation
On the JVM platform, the standard library contains extensions for reflection classes that provide a mapping to and from Java reflection objects (see package kotlin.reflect.jvm). For example, to find a backing field or a Java method that serves as a getter for a Kotlin property, you can write ...
🌐
JetBrains
youtrack.jetbrains.com › issue › KT-27928
Please make it possible to access java property values ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Handstandsam
handstandsam.com › 2023 › 02 › 01 › using-java-reflection-with-kotlin-companion-objects
Using Java Reflection with Kotlin Companion Objects – Handstand Sam
February 1, 2023 - val companionObjectInstance = companionObjectJavaClass.kotlin .companionObjectInstance!! Now that we have an instance of the companion object class, and know the Java class, we can use reflection to set the value of the enabled property on the companion object.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.reflect.jvm › java.lang.reflect.-field
java.lang.reflect.Field - Kotlin Programming Language
December 7, 2021 - Try the revamped Kotlin docs design! ... Returns a KProperty instance corresponding to the given Java Field instance, or null if this field cannot be represented by a Kotlin property (for example, if it is a synthetic field).
🌐
Rip Tutorial
riptutorial.com › getting values of all properties of a class
Kotlin Tutorial => Getting values of all properties of a class
Inter-operating with Java reflection · Referencing a class · Referencing a function · Setting values of all properties of a class · Regex · Singleton objects · Strings · Type aliases · Type-Safe Builders · Vararg Parameters in Functions · Visibility Modifiers · Bulk Insert · Bulk Delete · Bulk Update · Bulk Merge · Given Example class extending BaseExample class with some properties: open class BaseExample(val baseField: String) class Example(val field1: String, val field2: Int, baseField: String): BaseExample(baseField) { val field3: String get() = "Property without backing fie
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.properties › -read-write-property › set-value.html
setValue - Kotlin Programming Language
October 26, 2022 - Try the revamped Kotlin docs design! ... Sets the value of the property for the given object.
🌐
Medium
medium.com › @ramadan123sayed › kotlin-reflection-a-comprehensive-guide-f00417f2f521
Kotlin Reflection: A Comprehensive Guide | by Ramadan Sayed | Medium
August 12, 2024 - In this article, we’ll explore Kotlin reflection in depth, covering its basics, use cases, and practical examples, with a focus on how to leverage this feature effectively in real-world applications, including its common uses in Android development.
🌐
Reddit
reddit.com › r/kotlin › (reflections) get list of fields?
r/Kotlin on Reddit: (Reflections) Get list of fields?
February 7, 2015 -

Hey,

is there an equivalent for the java reflection foo.getClass().getFields() in Kotlin? I could only find that I can access a field when I know it's name, but I would like to handle fields in a generic way.

🌐
GeeksforGeeks
geeksforgeeks.org › kotlin-reflection
Kotlin Reflection - GeeksforGeeks
June 14, 2022 - In Kotlin, properties are a core feature of the language, providing a clean and concise way to encapsulate fields while maintaining control over how values are accessed or modified. Each property can have getters and setters, which are automatically generated but can be customized as needed.Kotlin P
Top answer
1 of 2
41

Answer

In short, you have to use Java reflection APIs in this case, and here is how to do it:

fun main() {
    val mainClass = MainClass()
    val f = MainClass::class.java.getDeclaredField("info")
    f.isAccessible = true
    f.set(mainClass, "set from reflection")
    mainClass.printInfo() // Prints "set from reflection"
}

class MainClass {
    private val info: String = "Hello"
    fun printInfo() = println(info)
}

Reason for using Java reflection APIs

It is not possible to do with Kotlin reflection APIs since no setter code is generated for a read-only (val) property. So to change it, we need to use Java reflection APIs which is more low-level. First, we use Tools -> Kotlin -> Show Kotlin Bytecode to see what the generated bytecode looks like. Then we see this:

// ================MainClass.class =================
// class version 50.0 (50)
// access flags 0x31
public final class MainClass {
  // access flags 0x12
  private final Ljava/lang/String; info = "Hello"
  // ...

i.e that the info fields in the MainClass Kotlin class causes the compiler to emit JVM code for a regular MainClass Java class with a final String info field. So to change it, we can use Java reflection APIs, as in the code above.

Kotlin reflection API attempt

If the field would have been private var you would be able to Use Kotlin reflection APIs like this:

f?.let {
    val mutableProp = it as KMutableProperty<*>
    it.isAccessible = true
    mutableProp.setter.call(mainClass, "set from Kotlin reflection")
    val w = it.get(mainClass) as String
    println(w)
}

but if you try this with private val you will get the below exception

Exception in thread "main" java.lang.ClassCastException: class kotlin.reflect.jvm.internal.KProperty1Impl cannot be cast to class kotlin.reflect.KMutableProperty (kotlin.reflect.jvm.internal.KProperty1Impl and kotlin.reflect.KMutableProperty are in unnamed module of loader 'app')
    at MainKt.main(main.kt:107)
    at MainKt.main(main.kt)

since no setter code is generated for val fields, and thus the info property will have a Kotlin Reflection API type of KProperty and not KMutableProperty.

2 of 2
-2

This is working solution

import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.memberProperties

class MySolution {

var name = ""
var email = ""
}

@Suppress("UNCHECKED_CAST")
fun main() {

//Dummy Result Set
val rs = mapOf<String,String>("name" to "My Name", "email" to "My Email")

val mySol = MySolution();
val xyzMp = MySolution::class.memberProperties;
xyzMp.forEach { mp ->
   val prop =  mp as KMutableProperty<String>
    prop.setter.call(mySol, rs[mp.name])
}

println(mySol.name)
println(mySol.email)
println("*****Enjoy*******")

output

My Name
My Email
**** *Enjoy*******
🌐
Kotlin Discussions
discuss.kotlinlang.org › support
Reflection and properties, checking for custom getters/setters - Support - Kotlin Discussions
July 20, 2021 - Hi all, So I’m using reflection to scrape classes for annotated properties, which I then use to inject automatically loaded resources. This seems to be working well, but I have a question about getters and setters in th…