vendredi 20 octobre 2017

How to change a member field with Kotlin reflection?

I'm porting a class from Java to Kotlin. This class declares hundreds of objects. Each object has a name property which is identical with the declared variable name of the object. Java reflection allows to use the declared name via reflection to set the object member name. Just saves one parameter in hundreds of constructors.

I try to do the same in Kotlin but can't figure out how to do the property setting. Here is some simplified test code:

package myPackage

import kotlin.reflect.full.companionObject
import kotlin.reflect.full.declaredMemberProperties

class MyTestObject() {

  var name: String = "NotInitialized"

  companion object {
    val Anton = MyTestObject()
    val Berta = MyTestObject()
    val Caesar = MyTestObject()
  }
}

fun main(args : Array<String>) {
  println(MyTestObject.Anton.name) // name not yet initialized

  // Initialize 'name' with the variable name of the object:
  for (member in MyTestObject::class.companionObject!!.declaredMemberProperties) {
    if (member.returnType.toString() == "myPackage.MyTestObject") {
      println("$member: ${member.name}")

      // Set 'name' property to 'member.name':
      // ???
    }
  }

  println(MyTestObject.Anton.name) // now with the initialized name
}

The ??? line is where I would like to get access to the name property of MyTestObject to set it to to member.name. I'm looking for a function similar to (member.toObject() as MyTestObject).name = member.name.





Aucun commentaire:

Enregistrer un commentaire