Tee*_*ker 5 java android kotlin
是否可以使用反射来访问对象的私有字段并在此字段上调用公共方法?
即
class Hello {
private World word
}
class World {
public BlaBlaBla foo()
}
Hello h = new Hello()
World world = reflect on the h
// And then
world.foo()
Run Code Online (Sandbox Code Playgroud)
Ser*_*gey 17
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
Run Code Online (Sandbox Code Playgroud)
使用这些扩展函数,我们可以访问类的私有属性和函数。例子:
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)
要在Kotlin 中使用反射添加依赖项:
实现“org.jetbrains.kotlin:kotlin-reflect:$kotlin_version”
s1m*_*nw1 12
可以使用反射制作private字段accessible.下面的例子(都写在Kotlin中)表明它......
使用Java反射:
val hello = Hello()
val f = hello::class.java.getDeclaredField("world")
f.isAccessible = true
val w = f.get(hello) as World
println(w.foo())
Run Code Online (Sandbox Code Playgroud)
使用Kotlin反射:
val hello = Hello()
val f = Hello::class.memberProperties.find { it.name == "world" }
f?.let {
it.isAccessible = true
val w = it.get(hello) as World
println(w.foo())
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3109 次 |
| 最近记录: |