繁体   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