Skip to content

Instantly share code, notes, and snippets.

@FavoRiteKK
Last active October 27, 2021 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FavoRiteKK/5806070a0ad14b9f0ca630e574d17a35 to your computer and use it in GitHub Desktop.
Save FavoRiteKK/5806070a0ad14b9f0ca630e574d17a35 to your computer and use it in GitHub Desktop.
Print a declarative string of given object.
@Test
fun testSoSo() {
val car = Car("me.car\ndmsklam", Engine("me.engine"), Wheel("me.wheel"))
println(printlnStr(car))
//OUTPUT:
// Car(
// engine = Engine(
// name = "me.engine"
// ),
// name = "me.car\ndmsklam",
// wheel = listOf(
// Wheel(
// name = "me.wheel"
// )
// )
// )
}
// The given object may be created from other forms, such as XML, JSON...
// This method will output a declaration string that creats the given object in Kotlin form.
private fun printlnStr(obj: Any?): String {
if (obj == null) return "null"
if (obj is String) return "\"${obj.replace("\n", "", true)}\""
val content: MutableList<String> = mutableListOf()
val propList = obj.javaClass.kotlin.memberProperties
val retStr: String = if (obj is List<*>) {
val list: List<*> = obj
for (elem in list) {
val tempStr = printlnStr(elem)
content.add("\n$tempStr")
}
"listOf(${content.joinToString()}\n)"
} else {
for (prop in propList) {
val tempStr = printlnStr(prop.get(obj))
content.add("\n${prop.name} = $tempStr")
}
"${obj.javaClass.name}(${content.joinToString()}\n)"
}
return retStr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment