Kotlin通过Java Reflection设置了懒惰的场

发布于 2025-02-11 03:17:11 字数 541 浏览 1 评论 0原文

我正在尝试在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北凤男飞 2025-02-18 03:17:11

只需创建一个像往常一样的懒惰< t>实例!

如果要将其设置为常量值newtree

tField.set(transaction, lazyOf(newTree))

您还可以设置一个新的代码块,以懒洋洋评估它:

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

Just create a Lazy<T> instance like you normally would!

If you want to set it to the constant value 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...
    }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文