kotlin reflection get list of fields

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.


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<T>, use the kotlin extension property to get the Kotlin KClass<T> 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.


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

Simple answer

In you build.gradle (app) file

implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlin_version")

And then

val fields = YourClass::class.declaredMemberProperties
for (i in fields){
    Log.e("Fields ===", i.name)
}

Cheers!!!