Last active
July 10, 2017 10:37
-
-
Save kamontat/4bc6dbb2917fe25e7e46e1930192fb5d to your computer and use it in GitHub Desktop.
medium source code
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
object GHObjectBuilder { | |
// build function | |
fun <T : Any> build(tClass: KClass<T>, json: JsonObject): T? { | |
// check primary constructor | |
if (tClass.primaryConstructor == null) return null | |
// create parameter mapping | |
val map: HashMap<KParameter, Any?> = HashMap<KParameter, Any?>() | |
// for each paramete in constructor | |
tClass.primaryConstructor!!.parameters.forEach { | |
param -> | |
// get annotation that is JsonKey class only!! | |
val keyAnnotation: JsonKey? = params.annotations.filter { | |
annotation -> | |
return@filter annotation.annotationClass == JsonKey::class | |
}.singleOrNull() as JsonKey | |
// get value inside json object | |
val value = json[keyAnnotation?.key] | |
// mapping param with value | |
map.put(param, value) | |
} | |
// create object with primary constructor | |
return tClass.primaryConstructor!!.callBy(map) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment