科特林反射获取字段列表 [英] kotlin reflection get list of fields
问题描述
在Kotlin中是否有Java反射foo.getClass().getFields()
的等效项?我只能在知道字段名称的情况下才能访问该字段,但是我想以一种通用的方式来处理字段.
is there an equivalent for the java reflection foo.getClass().getFields()
in Kotlin? I could only find that I can access a field when I know it's name, but I would like to handle fields in a generic way.
推荐答案
您想要字段作为支持字段"还是属性"作为字段?Kotlin实际上仅具有属性.您可以使用以下课程获得这些课程:
Did you want fields as-in "backing field" or fields as in "properties" ... Kotlin really only has properties. You can get these for some class using:
MyTest::class.memberProperties
// or
MyTest::class.declaredMemberProperties
然后从Java Class<T>
中使用kotlin
扩展属性来获取Kotlin KClass<T>
,您可以从中进行以下操作:
And from a Java Class<T>
, use the kotlin
extension property to get the Kotlin KClass<T>
from which you can proceed:
someClassOfMine.javaClass.kotlin.memberProperties
这也需要将kotlin-reflect
依赖项添加到您的构建和类路径中.您可以在KClass
This requires the kotlin-reflect
dependency as well to be added to your build and classpath. You'll find many other useful things on KClass
对于属性背后的秘密后备字段,使用Java反射的风险自负.
For the secret backing fields behind a property, use Java reflection at your own risk.
这篇关于科特林反射获取字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!