Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- companion object {
- val ATTRIBUTE_ANNOTATION_FIELDS = Attribute::class.java.declaredFields
- .filter { it.isAnnotationPresent(Value::class.java)}
- .groupBy { it.getDeclaredAnnotation(Value::class.java) }
- val TYPE = object : TypeToken<AttributeMap>() {}.type!!
- val SERIALIZER = JsonSerializer<AttributeMap> { src, _, _ -> src.serialize() }
- val DESERIALIZER = JsonDeserializer<AttributeMap> { json, _, _ -> deserialize(json.asJsonObject) }
- /**
- * Used to load an [AttributeMap] through [Gson].
- *
- * @param input the [JsonObject] that contains attribute data.
- * @return a new [AttributeMap] from the de-serialized [input].
- */
- fun deserialize(input : JsonObject) : AttributeMap {
- val output = AttributeMap()
- ATTRIBUTE_ANNOTATION_FIELDS.forEach { fields ->
- run {
- fields.value
- .map { it.get(null) as String }
- .filter { input.has(it) }
- .sortedBy { it.length }
- .forEach { name->
- val result = construct(fields.key.value)
- if(result is AttributeValueHolderTemplate) {
- result.deserialize(input.get(name))
- output.get(name, result)
- }
- }
- }
- }
- return output
- }
- /**
- * Used to construct a new instance of type [T] from the argument [kClass].
- *
- * @param kClass the [KClass] with type [T] of which the [KClass.primaryConstructor] is called.
- * @return a new object of type [T].
- */
- private fun <T : Any> construct(kClass: KClass<T>): T? {
- val ctor = kClass.primaryConstructor
- return if (ctor != null && ctor.parameters.isEmpty())
- ctor.call() else
- null
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement