Java 是否可以更改为Kotlin数据类生成的toString()方法的行为?
例如: 要排除或屏蔽密码或信用卡号等特殊属性,请执行以下操作:Java 是否可以更改为Kotlin数据类生成的toString()方法的行为?,java,kotlin,lombok,Java,Kotlin,Lombok,例如: 要排除或屏蔽密码或信用卡号等特殊属性,请执行以下操作: data class Key( val id: Int, val secret: String, val description: String? ) 或者忽略带有nulls的属性,以使生成的字符串更具可读性: Key( id = 1, secret = "foo", description = "bar" ).toString
data class Key(
val id: Int,
val secret: String,
val description: String?
)
或者忽略带有null
s的属性,以使生成的字符串更具可读性:
Key(
id = 1,
secret = "foo",
description = "bar"
).toString()
// Key(id=1, description=bar)
// or
// Key(id=1, secret=********, description=bar)
每次实现toString()
都可能非常繁琐且容易出错,尤其是当类中的属性太多时
这个问题有没有(即将推出的)解决方案(如Lombok for Java)?您可以尝试以下方法:
Key(
id = ...,
secret = ...,
description = null
).toString()
// Key(id=...)
// or
// Key(id=..., secret=...)
输出示例:我将安德烈·维多维琴科之前的回答改写如下:
data class Key(val id: Int, val secret: String, val description: String?){
override fun toString() = kotlinToString(properties = arrayOf(Key::id, Key::description)
}
哪个输出是
fun main(args : Array<String>) {
println(Key(1, "aa", "bbb").toString())
println(Key(1, "aa", null).toString())
}
可能您可以更改
kotlinToString
实现,以便在输出字符串中包含每类前缀,或者将其作为参数传递给kotlinToString
,但我希望这能对您有所帮助 关于使用扩展方法的问题可能与@LaksithaRanasingha重复,而这个问题没有。更重要的是,不要像这个问题那样询问如何在toString()
实现中最小化“繁琐且容易出错”的代码。一点也不重复。嗨@Victor,我提出的解决方案解决了你的问题,符合你的期望吗?
fun main(args : Array<String>) {
println(Key(1, "aa", "bbb").toString())
println(Key(1, "aa", null).toString())
}
id: 1, description: bbb, secret: aa
id: 1, secret: aa