0

Is there a native way in kotlin to access a nested complex object (parsed from JSON string) through a variable?

Smth similar to:

   var = "Obj4"
    a = Obj1.Obj2.Obj3.$var.Obj5.Array[index]

Thanks a lot in advance

Osolemio
  • 41
  • 1
  • 5
  • I think you're looking for reflextion. https://kotlinlang.org/docs/reference/reflection.html It's not dymanimacally-typed language where everything is map, so you'll need to find field with reflection. – asm0dey Nov 12 '18 at 19:01
  • Yep, I c. That would be like val name = p.javaClass.kotlin.memberProperties.first { it.name == "name" }.get(p) – Osolemio Nov 12 '18 at 19:05

1 Answers1

0

Taken from here

Using the reflection. Don't forget to add the dependency. Global inline extension fun for Any:

 inline fun <reified T : Any> Any.getThroughReflection(propertyName: String): T? {
    val getterName = "get" + propertyName.capitalize()
    return try {
        javaClass.getMethod(getterName).invoke(this) as? T
    } catch (e: NoSuchMethodException) {
        null
    }
}
Osolemio
  • 41
  • 1
  • 5