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

Ser*_*gey 8 reflection private private-functions private-methods kotlin

我想SomeClass从该类的外部调用该类的私有函数:

class SomeClass {
    private fun somePrivateFunction() {
        //...
    }

    private fun somePrivateFunctionWithParams(text: String) {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

在代码中的某个地方我引用了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
Run Code Online (Sandbox Code Playgroud)

如何从类外部调用 Kotlin 中带参数和不带参数的私有函数?

Ser*_*gey 8

我遇到了两个有用的扩展函数,它们使用反射:

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
Run Code Online (Sandbox Code Playgroud)

要在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())
Run Code Online (Sandbox Code Playgroud)


s1m*_*nw1 5

“私有”的想法是只有你可以在你的类中调用它。如果您想“闯入”该类,则需要利用反射:/sf/answers/3371134651/

来自文档:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 通过您提供的链接,我了解了如何访问对象的私有字段,但没有有关如何调用对象的私有函数的信息。 (2认同)