Kotlin – 为非数据类生成toString()

我有一个lateinit字段的类,所以它们不存在于构造函数中:

class ConfirmRequest() { lateinit var playerId: String } 

我想有toString()方法与所有领域,不想手动写入,以避免锅炉打印。 如果我使用Java,我会使用Lombok @ToString注释来解决这个问题。 有什么办法可以在Kotlin中实现吗?

推荐的方法是手动编写toString (或由IDE生成),并希望你没有太多这样的类。

data class的目的是为了适应85%的最常见的情况,其余15%的解决方案。

和你一样,我习惯于在Java中使用lombok作为toString()equals() ,所以有点失望,Kotlin中的非数据类需要所有的标准样板文件。

所以我创建了Kassava ,这是一个开源的库,可以让你实现toString()equals()而不需要任何样板文件 – 只需提供属性列表即可完成!

例如:

 // 1. Import extension functions import au.com.console.kassava.kotlinEquals import au.com.console.kassava.kotlinToString import java.util.Objects class Employee(val name: String, val age: Int? = null) { // 2. Optionally define your properties for equals()/toString() in a companion // object (Kotlin will generate less KProperty classes, and you won't have // array creation for every method call) companion object { private val properties = arrayOf(Employee::name, Employee::age) } // 3. Implement equals() by supplying the list of properties to be included override fun equals(other: Any?) = kotlinEquals( other = other, properties = properties ) // 4. Implement toString() by supplying the list of properties to be included override fun toString() = kotlinToString(properties = properties) // 5. Implement hashCode() because you're awesome and know what you're doing ;) override fun hashCode() = Objects.hash(name, age) } 

我发现Apache Commons Lang的ToStringBuilder的反射很有用,但是当我不需要(和一个叫做来自第三方lib的hashCode()生成NPE的时候,它会调用hashCode()和其他方法。

所以我只是跟着去

 // class myClass override fun toString() = MiscUtils.reflectionToString(this) // class MiscUTils fun reflectionToString(obj: Any): String { val s = LinkedList<String>() var clazz: Class<in Any>? = obj.javaClass while (clazz != null) { for (prop in clazz.declaredFields.filterNot { Modifier.isStatic(it.modifiers) }) { prop.isAccessible = true s += "${prop.name}=" + prop.get(obj)?.toString()?.trim() } clazz = clazz.superclass } return "${obj.javaClass.simpleName}=[${s.joinToString(", ")}]" } 

您可以定义一个包含要使用的数据的数据类,并通过委托给它来实现方法。

https://stackoverflow.com/a/46247234/97777