首页 > 解决方案 > Making a Kotlin Function Accept a String as an Object Reference

问题描述

I have a situation, where in Kotlin I want to take the name of a reference, modify it, and then call a function with the object, which corresponds with the modified name. For example:

val a = "Foo"
val aAlt = "Bar"

fun doSomething(s: String){ 
   println(s.*addAltToStringName()* ) 
}

So that by calling

doSomething(a)

the result is

Bar

I know, that doing something "untyped-scripty" like this in an object oriented language is dangerous, but I have other checks to prevent Nullpointers etc.

Thanks!

标签: classkotlinreference

解决方案


This can be done with reflection, but only if the argument to the function is property reference, so you can get its name. The String object itself would provide no way to retrieve info about whatever variables might hold references to it. In other words, your property a references a String object, but that String object itself has no name or knowledge of the property that references it.

class Test {
    val a = "Foo"
    val aAlt = "Bar"

    fun doSomething(s: KProperty<*>){
        val propertyName = s.name + "Alt"
        val propertyValue = Test::class.memberProperties.find { it.name == propertyName }?.get(this)
        println(propertyValue)
    }
}

fun main() {
    val test = Test()
    test.doSomething(test::a)
}

推荐阅读