要访问 Kotlin 中某个类的私有属性和函数,这里有两个有用的扩展函数:
inline fun <reified T> T.callPrivateFunc(name: String, vararg args: Any?): Any? =
T::class
.declaredMemberFunctions
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.call(this, *args)
inline fun <reified T : Any, R> T.getPrivateProperty(name: String): R? =
T::class
.memberProperties
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.get(this) as? R
使用示例:
class SomeClass {
private val world: World = World()
private fun somePrivateFunction() {
println("somePrivateFunction")
}
private fun somePrivateFunctionWithParams(text: String) {
println("somePrivateFunctionWithParams() text=$text")
}
}
class World {
fun foo(): String = "Test func"
}
// calling private functions:
val someClass = SomeClass()
someClass.callPrivateFunc("somePrivateFunction")
someClass.callPrivateFunc("somePrivateFunctionWithParams", "test arg")
// getting private member and calling public function on it:
val world = someClass.getPrivateProperty<SomeClass, World>("world")
println(world?.foo())
要在 Kotlin 中使用反射,请添加依赖项:
implementation “org.jetbrains.kotlin:kotlin-reflect:$kotlin_version”