Listing all the properties in a Kotlin class excluding the ones with custom getters

487 Views Asked by At

Is there a simple method I can use to list all of the properties in a class that don't implement a custom getter?


For example:
class Person(val name: String, val age: Int) {

    val signature: String get() = "$name - $age"
    
    val uuid = UUID.randomUUID()
}

Using the code above, I would like to find the following:

[ Person::name, Person::age, Person::uuid ].

2

There are 2 best solutions below

0
On

Properties that only have a getter do not have a JVM backing field, therefore; you can take all the properties, and exclude the ones that do not have a field.

// All properties
Person::class.declaredMemberProperties.forEach {
    println(it.name)
}
println()

// All fields
Person::class.java.declaredFields.forEach {
    println(it.name)
}
println()

It should be noted that the signature is missing from the second set.


0
On

Following code will return a list of all class properties with a backing fields and exclude all artificial properties.

Person::class.memberProperties.filter { it.javaField != null }