Kotlin通过Java Reflection设置了懒惰的场
我正在尝试在Kotlin进行Java反思,并且我在Kotlin课程中有以下领域:
val tree: Tree by lazy {
getTree(hashGroup, service)
}
我想通过Java Reflection设置此字段,到目前为止,我到了这一点:
val tField = transaction::class.java.getDeclaredField("tree\$delegate")
tField.isAccessible = true
tField.set(transaction, newTree)
显然,这还没有进行要工作,因为tree
字段具有委托(tree $ demegate
),并且希望我将其设置为懒惰
class类型而不是树
类型。
我知道最简单的是,在主类中实际添加了此字段的设置器,但是我无法真正修改API,我需要此固定剂用于弹性测试案例。这甚至可以做吗?
I'm trying to play around with Java reflection in Kotlin, and I have the following field in my Kotlin class:
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:
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.
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. Is this even possible to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需创建一个像往常一样的
懒惰< t>
实例!如果要将其设置为常量值
newtree
:您还可以设置一个新的代码块,以懒洋洋评估它:
Just create a
Lazy<T>
instance like you normally would!If you want to set it to the constant value
newTree
:You can also set a new block of code for it to be evaluated lazily: