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())
)
?: takes the right-hand value if the left-hand value is null (the elvis operator). :: creates a member reference or a class reference.
note. Kotlin/JS provides limited support for reflection features. Learn more about reflection in Kotlin/JS.
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.
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.
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.
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.
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