反思:如何从 kotlin 伴生对象获取私有字段的值?

问题描述 投票:0回答:1

我想要一个扩展,允许我从

dataMap
获取私有字段
companion object
的值以进行单元测试。

带有伴生对象的类:

@Service
class BroadcastServiceImpl {
    companion object : KLogging() {
        private val dataMap: MutableMap<String, MutableSet<UserData>> = mutableMapOf()
    }
}

我用反射写了这样一个方法。但它有一个编译错误。我什至无法想象如何解决它

private fun BroadcastServiceImpl.getDataMap(): Map<String, Set<UserData>> {
    return javaClass.getDeclaredField("dataMap").let {
        it.isAccessible = true
        val value = it.get(this)
        return@let value;
    }
}

编译错误:

Type mismatch.
Required:
Map<String, Set<UserData>>
Found:
Any!
kotlin reflection
1个回答
0
投票

它帮助我获得了字段值

val field = BroadcastServiceImpl::class.java.getDeclaredField("dataMap")
field.isAccessible = true
return field.get(null) as (HashMap<String, Set<UserData>>)
© www.soinside.com 2019 - 2024. All rights reserved.