reflection - 通过 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)
但这在本机环境中不起作用。
解决方案
我只是通过文档,所以下面可能有点错误,但你可以试试这个:
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
}
推荐阅读
- angular - PrimeNg 组织结构图:删除选定节点
- arrays - 将对象数组转换为 csv
- javascript - Javascript:使用 x-www-form 在对象中获取和发布数组
- dbeaver - DBeaver 转储和还原 GENERATED 列的问题
- python - Pandas:使用元组作为标签从唯一的行值对创建列
- firebase - 为未经身份验证的用户设置 Firebase 安全规则
- javascript - 如何通过 DateObject 在日期数组中找到最近的过去或未来日期?
- c# - 方法中的参数位置 - 参数 VS CancellationToken
- python - 在 python 中使用 GDAL_retile 平铺卫星图像?
- android - 在 Android 中平滑滚动到自定义视图