1

我想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 中带参数和不带参数的私有函数?

4

1 回答 1

4

“私人”的想法是只有你可以在你的课堂上调用它。如果您想“闯入”该课程,则需要使用反射: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()))
    }

}
于 2019-12-17T09:19:17.603 回答