Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.04 KB | None | 0 0
  1. companion object {
  2.         val ATTRIBUTE_ANNOTATION_FIELDS = Attribute::class.java.declaredFields
  3.             .filter { it.isAnnotationPresent(Value::class.java)}
  4.             .groupBy { it.getDeclaredAnnotation(Value::class.java) }
  5.         val TYPE = object : TypeToken<AttributeMap>() {}.type!!
  6.         val SERIALIZER = JsonSerializer<AttributeMap> { src, _, _ -> src.serialize() }
  7.         val DESERIALIZER = JsonDeserializer<AttributeMap> { json, _, _ -> deserialize(json.asJsonObject) }
  8.         /**
  9.          * Used to load an [AttributeMap] through [Gson].
  10.          *
  11.          * @param input the [JsonObject] that contains attribute data.
  12.          * @return a new [AttributeMap] from the de-serialized [input].
  13.          */
  14.         fun deserialize(input : JsonObject) : AttributeMap {
  15.             val output = AttributeMap()
  16.             ATTRIBUTE_ANNOTATION_FIELDS.forEach { fields ->
  17.                 run {
  18.                     fields.value
  19.                         .map { it.get(null) as String }
  20.                         .filter { input.has(it) }
  21.                         .sortedBy { it.length }
  22.                         .forEach { name->
  23.                             val result = construct(fields.key.value)
  24.                             if(result is AttributeValueHolderTemplate) {
  25.                                 result.deserialize(input.get(name))
  26.                                 output.get(name, result)
  27.                             }
  28.                         }
  29.                 }
  30.             }
  31.             return output
  32.         }
  33.         /**
  34.          * Used to construct a new instance of type [T] from the argument [kClass].
  35.          *
  36.          * @param kClass the [KClass] with type [T] of which the [KClass.primaryConstructor] is called.
  37.          * @return a new object of type [T].
  38.          */
  39.         private fun <T : Any> construct(kClass: KClass<T>): T? {
  40.             val ctor = kClass.primaryConstructor
  41.             return if (ctor != null && ctor.parameters.isEmpty())
  42.                 ctor.call() else
  43.                 null
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement