Kotlin - generate toString() for a non-data class

后端 未结 6 955
终归单人心
终归单人心 2020-12-17 08:17

Situation:

I have a class with lateinit fields, so they are not present in the constructor:

class ConfirmRequest() {
           


        
6条回答
  •  孤城傲影
    2020-12-17 08:22

    This is what I endup doing.

    Create extension function on Any class

    fun Any.toStringByReflection(exclude: List = listOf(), mask: List = listOf()): String {
        val propsString = this::class.memberProperties
                .filter { exclude.isEmpty() || !exclude.contains(it.name) }
                .joinToString(", ") {
                    val value = if (!mask.isEmpty() && mask.contains(it.name)) "****" else it.getter.call(this).toString()
                    "${it.name}=${value}"
                };
    
        return "${this::class.simpleName} [${propsString}]"
    }
    

    Then you can call this method from individual type.

    override fun toString(): String {
        return this.toStringByReflection()
    }
    

    It generates string below

    Table [colums=[], name=pg_aggregate_fnoid_index, schema=pg_catalog, type=SYSTEM INDEX]
    

    With name field masked:

    override fun toString(): String {
        return this.toStringByReflection(mask= listOf("name"))
    }
    

    It generates,

    Table [colums=[], name=****, schema=pg_catalog, type=SYSTEM INDEX]
    

提交回复
热议问题