【问题标题】:How to modify property of companion object in Kotlin?如何在 Kotlin 中修改伴生对象的属性?
【发布时间】:2021-01-18 10:41:21
【问题描述】:

我有一个包含如下伴随对象的类。

class Customization {
    companion object {
        var become_member = ""
    }
}

我想在运行时修改伴生对象的属性。我将在这个类中添加数百个属性。所以我必须做动态。我使用了这种方法并得到如下错误。

fun customizeStrings(key:String, value:String){
    var buckTypes = Customization::class
    var buck = Customization()
    var variableToInvoke  = buckTypes.companionObject!!.memberProperties.find {
        it.name == key
    }
    println(variableToInvoke!!.name)

    if (variableToInvoke  is KMutableProperty<*>) {
     variableToInvoke.setter.call(buck, value) 
    }

}

我收到了这个错误。

org.koin.core.error.InstanceCreationException:无法为 [Factory:'com.screen.splash.SplashViewModel'] 创建实例

谁能向我解释我的错在哪里?或者告诉我另一种在 Kotlin 中修改伴生对象属性的方法?

【问题讨论】:

  • 这里的第一个参数必须是什么? ->setter.call(Customization.Companion, value)。但是我不知道这个错误与这个有什么关系......而且可能不是从其父级访问同伴,您可以直接定位同伴:Customization.Companion::class
  • @AnimeshSahu 感谢您的回复。很有趣,但效果很好。

标签: kotlin properties edit koin companion-object


【解决方案1】:

正如@AnimeshSahu 在评论中所说,它很有效。如果像我这样的人出现错误,请尝试直接访问目标伴侣,如Customizationn.Companion::class。它拯救了我的一天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2020-03-09
    • 1970-01-01
    • 2021-03-25
    • 2016-11-02
    • 1970-01-01
    相关资源
    最近更新 更多