【发布时间】:2020-09-13 12:42:30
【问题描述】:
我正在尝试为detekt project 创建新规则。为此,我必须知道 Kotlin 属性的确切类型。例如,val x: Int 的类型为 Int。
不幸的是,对于private val a = 3 类型的属性,我收到以下信息:
-
property.typeReference是null -
property.typeParameters为空 -
property.typeConstraints为空 -
property.typeParameterList为空 -
property.text是private val a = 3 -
property.node.children().joinToString()具有上一项的对象符号 -
property.delegate为空 -
property.getType(bindingContext)为 null(属性bindingContext是使用的KtTreeVisitorVoid的一部分
问题:如何获取类型名称(或者更好的是对象KClass)来比较实际属性类型和Boolean 类类型? (例如,我只需要获取 if property boolean of not)
代码:
override fun visitProperty(property: org.jetbrains.kotlin.psi.KtProperty) {
val type: String = ??? //property.typeReference?.text - doesn't work
if(property.identifierName().startsWith("is") && type != "Boolean") {
report(CodeSmell(
issue,
Entity.from(property),
message = "Non-boolean properties shouldn't start with 'is' prefix. Actual type: $type")
)
}
}
【问题讨论】:
标签: kotlin reflection compiler-construction detekt