Search code examples
kotlindata-class

How to check numbers of property in Kotlin data class?


As the title, I want to check how many properties in a Kotlin data class. Its use case is to ensure the Mapper from DTO to Data Model is implemented correctly.


Solution

  • By default reflection library is not addend in kotlin standard library to reduce the size, if we need to use reflection we need to add that library explicitly which can be done by adding

        runtime group: 'org.jetbrains.kotlin', name: 'kotlin-reflect'
    

    to your dependencies.

    And for getting members of a data class we can now use

    DataClassExample::class.members
    

    If u don't want to add any extra library u can use java Reflection, which is generally not recommended

    DataClassExample::class.java.declaredFields