title: How to change a member field with Kotlin reflection?
body: <p>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 <code>name</code>. Just saves one parameter in hundreds of constructors.</p>
  
  <p>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:</p>
  
  <pre><code>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&lt;String&gt;) {
      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
  }
  </code></pre>
  
  <p>The <code>???</code> line is where I would like to get access to the <code>name</code> property of <code>MyTestObject</code> to set it to to <code>member.name</code>. I'm looking for a function similar to <code>(member.toObject() as MyTestObject).name = member.name</code>.</p>