mardi 2 avril 2019

Issue while using kotlin reflaction to map object member properties to hashmap

open class Test {

    fun getAsHashMap() : HashMap<String, Any> {
        val hashMap = HashMap<String, Any>()
        val className = this.javaClass.kotlin

        for (prop in className::class.memberProperties) {
            val field = className::class.java.getDeclaredField(prop.name)
            val fieldSerializedName : SerializedName? = field.getAnnotation(SerializedName::class.java)
            fieldSerializedName?.let {
                hashMap[fieldSerializedName.value] = prop.get(this)!!
            } ?: run {
                hashMap[prop.name] = prop.get(this)!!
            }
        }

        return hashMap
    }


  }

I have wrote above function to map the memberProperties of object instance of its child class to hashmap. It either uses serialized name of the member or prop name [Based on availability of serialized name for that property] But unfortunately I get the following error. Error This is my first time using reflection java/kotlin, please let me know if it can be fixed.





Aucun commentaire:

Enregistrer un commentaire