Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin reflection get list of fields

Tags:

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.

like image 982
fwilhe Avatar asked Feb 08 '15 08:02

fwilhe


People also ask

Does Kotlin support reflection?

note. Kotlin/JS provides limited support for reflection features. Learn more about reflection in Kotlin/JS.

What is the :: in Kotlin?

?: takes the right-hand value if the left-hand value is null (the elvis operator). :: creates a member reference or a class reference.

How does reflection work in Kotlin?

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.


2 Answers

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.

like image 161
Jayson Minard Avatar answered Oct 15 '22 21:10

Jayson Minard


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 
like image 26
arkoak Avatar answered Oct 15 '22 22:10

arkoak