检查会员/财产类型 [英] Check type of member/property
问题描述
假设我有任何一门课,像这样一课:
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?
推荐答案
由于Kotlin没有字段,而只有带有支持字段的属性,因此应检查该属性的返回类型.
Since Kotlin does not have fields but only properties with backing fields, you should check the return type of the property.
尝试一下:
class SomeClass(val aThing: String, val otherThing: Double)
for(property in SomeClass::class.declaredMemberProperties) {
println("${property.name} ${property.returnType}")
}
更新:
如果该类在没有后备字段的情况下不使用自定义getter和/或setter,则可以这样获取后备字段的类型:
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
作为一个完整的示例,这是您的类,带有一个名为foo的附加val属性,该属性带有自定义getter(因此不会创建任何后备字段).您将看到该属性的getJavaField()将返回null.
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:
使用String::class.createType()
将为每个KClass返回KType,因此您可以使用例如property.returnType == String::class.createType()
查明它是否是(kotlin)字符串.
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.
这篇关于检查会员/财产类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!