Check type of member/property

爷,独闯天下 提交于 2019-12-30 09:39:33

问题


Let's say i have any class, like this one:

class SomeClass(val aThing: String, val otherThing: Double)

Then I use reflection to analyze the fields of this class:

for(field in SomeClass.declaredMemberProperties){

}

How can I check the type of each field?


回答1:


Since Kotlin does not have fields but only properties with backing fields, you should check the return type of the property.

Try this:

    class SomeClass(val aThing: String, val otherThing: Double)

    for(property in SomeClass::class.declaredMemberProperties) {
        println("${property.name} ${property.returnType}")
    }

UPDATE:

If the class does not use custom getters and/or setters without backing fields, you can get the type of the backing field like this:

property.javaField?.type

As a complete example, here is your class with an additional val property called foo with a custom getter (so no backing field is created). You will see that getJavaField() of that property will return null.

    class SomeClass(val aThing: String, val otherThing: Double) {
        val foo : String
            get() = "foo"
    }

    for(property in SomeClass::class.declaredMemberProperties) {
        println("${property.name} ${property.returnType} ${property.javaField?.type}")
    }

UPDATE2:

Using String::class.createType() will return the KType for every KClass, so you can use e.g. property.returnType == String::class.createType() to find out if it's a (kotlin) String.



来源:https://stackoverflow.com/questions/48383153/check-type-of-member-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!