美文网首页
Android Kotlin 反射工具

Android Kotlin 反射工具

作者: 想看烟花么 | 来源:发表于2023-06-14 16:02 被阅读0次
inline fun <reified T> Any.getPrivateField(fieldName: String): T? {
    return this::class.memberProperties.find { fieldName == it.name }?.apply {
        isAccessible = true
    }?.getter?.call(this) as T?
}

fun Any.invokePrivateField(fieldName: String, data: Any) {
    (this::class.memberProperties.find { fieldName == it.name }?.apply {
        isAccessible = true
    } as? KMutableProperty<*>)?.setter?.call(this, data)
}

inline fun <reified T> T.invokePrivateMethod(methodName: String, vararg args: Any?): Any? {
    val method = T::class.functions.firstOrNull{ (it.name == methodName && (it.parameters.size - 1) == args.size)} ?: T::class.superclasses.map { it.functions.firstOrNull{ method-> (method.name == methodName && (method.parameters.size - 1) == args.size)} }.firstOrNull()
    method?.isAccessible = true
    return method?.call(this, *args)
}

-----------------------------End-----------------------------

感谢您的耐心阅读,欢迎支持与点赞。

相关文章

网友评论

      本文标题:Android Kotlin 反射工具

      本文链接:https://www.haomeiwen.com/subject/fkqkydtx.html