Created
June 19, 2017 11:56
-
-
Save odiak/a34235accb25779094836b6e02f0cfd1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import kotlin.reflect.KClass | |
import kotlin.reflect.full.memberProperties | |
open class A { | |
val a = "xxxx" | |
var b = 12 | |
} | |
class B : A() { | |
val c: String? = null | |
} | |
fun <T : Any> T.toMap(): Map<String, String?> { | |
@Suppress("unchecked_cast") | |
val klass: KClass<T> = this::class as KClass<T> | |
val map = mutableMapOf<String, String?>() | |
klass.memberProperties.forEach { p -> | |
map[p.name] = p(this)?.toString() | |
} | |
return map | |
} | |
fun main(args: Array<String>) { | |
val b = B() | |
println(b.toMap()) // {c=null, a=xxxx, b=12} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment