首页 > 解决方案 > 通过 Kotlin 中的反射获取成员变量

问题描述

如果我在 Kotlin 上课:

class Foo{

var x= null
var y=null

}

我想通过反射检查这些成员中的哪些已在运行时设置。我可以遍历它们并在 Java 中检查 null。

Foo foo= new Foo();

//this gives me the value of foo.x
Foo.class.getDeclaredField("x").get(foo);

如何在 Kotlin/Native 中做同样的事情?我知道我可以在 Android 中通过

Foo::class.java.getDeclaredField("x").get(foo)

但这在本机环境中不起作用。

标签: reflectionkotlin

解决方案


我只是通过文档,所以下面可能有点错误,但你可以试试这个:

val prop : KCallable = Foo::class.members.firstOrNull { it.name == "x" }
if (prop != null) {
   val xValue : Int? = prop.call(object)
    //you have to declare the type of the xValue
}

推荐阅读