Check type of member/property

2019-02-18 07:11发布

问题:

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.