How to get property of object dynamically in kotlin

Viewed 446

Say for example I have the following object...

val ob = Thread.currentThread().getStackTrace()[2]

...and I want to select a property from this via a dynamic variable. ob.<property> would work normally but what if I didn't know <property> at compile time?

Is it possible to run something like ob[<property:str>] (as is the case in javascript, python etc) in kotlin?

1 Answers

Yes it is, there is a nice library kpropmap. We use it on production because we just need to have a Map<String, *>, but I wouldn't recommend using it for accessing fields.

https://github.com/rocketraman/kpropmap https://mvnrepository.com/artifact/com.github.rocketraman/kpropmap

After adding a dependency you can just write

val map = propMapOf(obj)
val name = map["name"]

However it'd much better if you were able to cast the obj to some known type and access the property statically

(obj as? SomeInterface)?.name
Related