https://kotlinlang.org logo
#announcements
Title
# announcements
k

Krzysztof Kocel

07/18/2019, 9:14 AM
I have an object:
Copy code
class User {
      var id: String? = null
      var name: String? = null
    }
and list of pairs:
Copy code
val fieldsToChange = listOf<Pair<String, String>>(Pair("name", "foo"), Pair("id", "bar"))
I would like to iterate trough list of pairs and set appropriate values for given properties using reflection. How I can achieve this using kotlin reflection?
k

kralli

07/18/2019, 9:24 AM
What do you need it for? If you’re just trying it out to learn something, then it’s relatively simple. But if you need this for production code, you might want to use an library for this instead of writing it yourself.
k

Krzysztof Kocel

07/18/2019, 9:28 AM
I have this particular use case - I have field name and value in input string and I want to access field of object by name
d

diesieben07

07/18/2019, 9:42 AM
User::class.memberProperties.find { it.name == "name" }
k

Karolis

07/18/2019, 9:49 AM
@Krzysztof Kocel I've answered with a bit more details in SO ( https://stackoverflow.com/questions/57090841/set-property-by-string-in-kotlin-using-reflection/57091296#57091296 ). But I totally agree with Iven that it might be better to use a library
👍 1