Is it possiable to use reflection to access a object's private field and call a public methods on this field?

i.e

class Hello {
   private World word
}

class World {
   public BlaBlaBla foo()
}

Hello h = new Hello()

World world = reflect on the h


// And then 

world.foo()

推荐答案

使用反射可以使private个字段变为accessible.下面的例子(都写在Kotlin中)展示了它...

Using Java Reflection:

val hello = Hello()
val f = hello::class.java.getDeclaredField("world")
f.isAccessible = true
val w = f.get(hello) as World
println(w.foo())

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

Kotlin相关问答推荐

Kotlin-stdlib中的模拟扩展函数

如何在Docker中使用Selenium和chromedriver?

Kotlin接口方法默认值&;可传递依赖项

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

通用接口继承

将 SharedPreferences 中的值公开为流

Jetpack Compose:当状态从另一个活动改变时强制重组

Kotlin 编译器在构造函数中报告未使用的表达式,以便构建器采用 vararg lambda

如何通过 compose 处理剪切区域?

如何使用 Kotlin KClass 属性 simpleName 生成空值

如何为你的 Flutter 元素添加 Kotlin 支持?

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

如何使 TextInputEditText 只读?

Android插件2.2.0-alpha1无法使用Kotlin编译

Kotlin中具有多个参数的绑定适配器

以Kotlin为单位的货币数据类型

在 Kotlin 函数上使用 Mokito anyObject() 时,指定为非 null 的参数为 null

@StringRes、@DrawableRes、@LayoutRes等android注释使用kotlin参数进行判断

项目不会使用 Kotlin 1.1.3 构建