Skip to content

Instantly share code, notes, and snippets.

@kamontat
Last active July 10, 2017 10:37
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 kamontat/4bc6dbb2917fe25e7e46e1930192fb5d to your computer and use it in GitHub Desktop.
Save kamontat/4bc6dbb2917fe25e7e46e1930192fb5d to your computer and use it in GitHub Desktop.
medium source code
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