我想要一个扩展,允许我从
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!
它帮助我获得了字段值
val field = BroadcastServiceImpl::class.java.getDeclaredField("dataMap")
field.isAccessible = true
return field.get(null) as (HashMap<String, Set<UserData>>)