Skip to content

Instantly share code, notes, and snippets.

@waqasakram117
Last active March 2, 2020 12:07
Show Gist options
  • Select an option

  • Save waqasakram117/73392511f166149eaaf593310c59c9cd to your computer and use it in GitHub Desktop.

Select an option

Save waqasakram117/73392511f166149eaaf593310c59c9cd to your computer and use it in GitHub Desktop.
/**
*
* @param to source class
* @param from convert source class fields to this
* @param mapper used to bypass specific field to another field
*/
fun <U: Any> convertInto(to:Any, from :KClass<U>, mapper:Map<String, String> = hashMapOf()):U{
if (from.isData.not()) throw IllegalAccessException("from class must be data class")
val fields = to::class.java.declaredFields
val valueMap = HashMap<String, Any>()
fields.filter { it.isAnnotationPresent(SerializedName::class.java) }
.forEach {
val ann= it.annotations[0] as SerializedName
it.isAccessible = true
ann.value.let {v ->
var mapKey:String = v
if (mapper.containsKey(mapKey)){
mapKey = mapper[mapKey] ?: ""
}
valueMap[mapKey] = it.get(to)
}
}
valueMap
val fromClazz = from.java
val ob = fromClazz.newInstance()
fromClazz.declaredFields.filter { it.isAnnotationPresent(SerializedName::class.java) }
.forEach {
val ann= it.annotations[0] as SerializedName
it.isAccessible = true
if (valueMap.containsKey(ann.value)){
it.set(ob , valueMap[ann.value])
}
}
return ob
}
data class A(@SerializedName("name")val name:Int, @SerializedName("roll") val rollNumber:String)
data class B(@SerializedName("rollnumber") val n:String = "dummy")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment