Last active
October 27, 2021 15:14
-
-
Save FavoRiteKK/5806070a0ad14b9f0ca630e574d17a35 to your computer and use it in GitHub Desktop.
Print a declarative string of given object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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