kotlin reflection get list of fields

后端 未结 4 2297
情书的邮戳
情书的邮戳 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:30

    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
    

    And from a Java Class, use the kotlin extension property to get the Kotlin KClass from which you can proceed:

    someClassOfMine.javaClass.kotlin.memberProperties
    

    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

    For the secret backing fields behind a property, use Java reflection at your own risk.

提交回复
热议问题