简体   繁体   English

Kotlin 通过 Java 反射设置惰性字段

[英]Kotlin set lazy field through Java reflection

I'm trying to play around with Java reflection in Kotlin, and I have the following field in my Kotlin class:我正在尝试在 Kotlin 中使用 Java 反射,并且我的 Kotlin 类中有以下字段:

val tree: Tree by lazy { 
    getTree(hashGroup, service) 
}

I'd like to set this field through Java reflection, and so far I got to this point:我想通过Java反射设置这个字段,到目前为止我已经到了这一点:

val tField = transaction::class.java.getDeclaredField("tree\$delegate")
tField.isAccessible = true
tField.set(transaction, newTree)

Obviously this is not going to work, because the tree field has a delegate ( tree$delegate ) and it wants me to set it to a Lazy class type and not Tree type.显然这是行不通的,因为tree字段有一个委托( tree$delegate ),它希望我将它设置为Lazy类类型而不是Tree类型。

I know the easiest would be to actually add a setter for this field in the main class but I can't really modify the API and I need this for a resilience test case.我知道最简单的方法是在主类中为这个字段添加一个设置器,但我不能真正修改 API,我需要这个来进行弹性测试用例。 Is this even possible to do?这甚至可能吗?

Just create a Lazy<T> instance like you normally would!只需像往常一样创建一个Lazy<T>实例!

If you want to set it to the constant value newTree :如果要将其设置为常量值newTree

tField.set(transaction, lazyOf(newTree))

You can also set a new block of code for it to be evaluated lazily:您还可以设置一个新的代码块以对其进行延迟评估:

tField.set(transaction, lazy {
    Tree().apply {
        // do something lazily to this tree...
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM