簡體   English   中英

使用Kotlin反思將對象成員屬性映射到hashmap時出現問題

[英]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
    }


  }

我已經編寫了上面的函數來將其子類的object instance的memberProperties hashmaphashmap 它要么使用成員的序列化名稱,要么使用prop名稱。[基於該屬性的序列化名稱的可用性],但是不幸的是,我收到以下錯誤。 錯誤 這是我第一次使用反射java / kotlin,請讓我知道它是否可以修復。

編輯1:

如果我像這樣直接使用this.javaClass.kotlin的名稱,它將非常有效

data class ProductInformation (
        @field:SerializedName("productid")
        val productId: Int,
        @field:SerializedName("productname")
        val productName: String,
        @field:SerializedName("brandname")
        val brandName: String,
        @field:SerializedName("originalprice")
        val originalPrice: Int,
        @field:SerializedName("sellingprice")
        val sellingPrice: Int,
        @field:SerializedName("productgender")
        val productGender: String,
        @field:SerializedName("productvariant")
        val productVariant: String,
        @field:SerializedName("discounted")
        val discounted: String,
        @field:SerializedName("productcategory")
        val productCategory: String
) : StructuredEventAttribute {

    override fun getAsHashMap(): HashMap<String, Any> {
        val hashMap = HashMap<String, Any>()

        for (prop in ProductInformation::class.memberProperties) {
            val field = ProductInformation::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
    }

}

interface StructuredEventAttribute {
    fun getAsHashMap() : HashMap<String, Any>
}

它工作得很好

ProductInformation::class.memberProperties返回ProductInformation類成員屬性的集合。

className::class.memberProperties (其中className = this.javaClass.kotlin )返回className類的成員屬性的集合,該類是KClass<out Test> 簡而言之,您將獲得KClass成員,而不是Test

解決方案:將className::class.memberProperties更改為className.memberProperties

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM