Kotlin reflection - getting all field names of a Class
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.
Use MyClass::class.java.declaredFields
or it's instance: myObject::class.java.declaredFields
.
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.