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.
note. Kotlin/JS provides limited support for reflection features. Learn more about reflection in Kotlin/JS.
?: takes the right-hand value if the left-hand value is null (the elvis operator). :: creates a member reference or a class reference.
In Kotlin, Reflection is a combination of language and library capabilities that allow you to introspect a program while it's running. Kotlin reflection is used at runtime to utilize a class and its members, such as properties, methods, and constructors.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With