如何在 Kotlin 中从类外部调用类的私有函数



我想从这个类之外调用类SomeClass的私有函数:

class SomeClass {
private fun somePrivateFunction() {
//...
}
private fun somePrivateFunctionWithParams(text: String) {
//...
}
}

在代码中的某个地方,我引用了SomeClass对象:

val someClass = SomeClass()
// how can I call the private function `somePrivateFunction()` from here?
// how can I call the private function `somePrivateFunctionWithParams("some text")` from? here

如何在类外部调用 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

要在Kotlin中使用反射,请添加依赖项:

实现 "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version">

这些函数可以按如下方式使用:

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())

"private"的想法是,只有你可以在你的类中调用它。如果你想"闯入"该类,你需要利用反射:https://stackoverflow.com/a/48159066/8073652

从文档中:

private表示仅在此类中可见(包括其所有成员(

下面是一个示例:

class WithPrivate {
private fun privFun() = "you got me"
}
fun main() {
WithPrivate::class.declaredMemberFunctions.find { it.name == "privFun" }?.let {
it.isAccessible = true
println(it.call(WithPrivate()))
}
}
val managerClass = Class.forName("com.api.Manager").kotlin
val managerInstance = managerClass.createInstance()
val startMethod = managerClass
.declaredMemberFunctions
.first { it.name == "start" }
.also { it.isAccessible = true }
val param = 1234
startMethod.call(managerInstance, param)

相关内容

  • 没有找到相关文章

最新更新