class - 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!
解决方案
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)
}
推荐阅读
- python - 根据另一个列值创建一个 pandas 数据框列
- php - 找不到包 php7.3-gd
- computer-vision - Google colab:RuntimeError:后端 CPU 的预期对象,但为参数 #4 'mat1' 获得了后端 CUDA
- biztalk - BizTalk - 绑定属性 -“useAmbientTransaction” = False
- oracle - 如何在 oracle apex 中取消隐藏页面项目
- sql - Hive 排序数组列相对于同一表中的其他数组列
- tcl - 使用 upvar 从 proc 中提取变量
- angular - 当我尝试制作中间件进行身份验证时发生错误
- laravel - 根据 LARAVEL 中的会话数据将用户重定向到不同的页面
- ionic-framework - 为什么不显示我的 ion-select 的默认值?