kotlin reflection get list of fields

后端 未结 4 2274
情书的邮戳
情书的邮戳 2021-02-18 20:51

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

4条回答
  •  面向向阳花
    2021-02-18 21:19

    Very easy now with Kotlin v1.1, You can use the following method to get the fields in kotlin

    val fields = MyClass.javaClass.kotlin.members
    

    Where MyClass is the class of your choice.

    In order to use this you need to have kotlin-reflect included in your gradle build file as below

    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    

    Additionally, it is also possible to get the fields from the javaClass directly if you need java fields (useful in some cases as these cover a slightly different scope)

    val fields = MyClass.javaClass.declaredFields
    

提交回复
热议问题