Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin reflection - getting all field names of a Class

Tags:

How can I get a list of a Kotlin data class it's declaredFields? Like Java's getDeclaredFields()

And if this is possible is it also possible to filter for public and private fields? (Like Java's Modifier.isPrivate(field.getModifiers()))

like image 496
Ivar Reukers Avatar asked Sep 20 '16 08:09

Ivar Reukers


People also ask

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.

Does Kotlin support reflection?

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

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.

What is a reference in Kotlin?

Kotlin stores all variables in memory twice - in the stack and then in the heap. In the stack, only the reference is stored, i.e. a link to the heap, where the real object is stored. Both stack and heap are located in the RAM memory. The difference is in the access and in the size.


2 Answers

Probably what you want is to get properties of a class, not fields. This can be done as follows:

MyClass::class.declaredMemberProperties

Getting fields is also possible through Java reflection:

MyClass::class.java.declaredFields

But fields are rather an implementation detail in Kotlin, because some properties might have no backing field.


As to the visibility, for properties you can check the getter visibility modifiers:

val p = MyClass::class.declaredMemberProperties.first()
val modifiers = p.javaGetter?.modifiers

Note: it's null in case of a simple private val or @JvmField usage. Then you can inspect p.javaField instead.

Then, if modifiers is not null, just check it with Modifier.isPrivate(...).

Properties in Kotlin can have separate visibility modifiers for getter and setter, but a setter access cannot be more permissive than that of the getter, which is effectively the property visibility.

like image 103
hotkey Avatar answered Oct 11 '22 03:10

hotkey


There is indeed documentation available for Kotlin reflection: an overall summary of reflection and the API docs including for the KClass.members function. You can also jump to the declaration of that method and you will see it is documented in the source code as well.

like image 24
Jayson Minard Avatar answered Oct 11 '22 05:10

Jayson Minard