【问题标题】:Retrieve Kotlin Property type from Kotlin psi API从 Kotlin psi API 检索 Kotlin 属性类型
【发布时间】:2020-09-13 12:42:30
【问题描述】:

我正在尝试为detekt project 创建新规则。为此,我必须知道 Kotlin 属性的确切类型。例如,val x: Int 的类型为 Int。

不幸的是,对于private val a = 3 类型的属性,我收到以下信息:

  1. property.typeReference 是 null
  2. property.typeParameters 为空
  3. property.typeConstraints 为空
  4. property.typeParameterList 为空
  5. property.text 是 private val a = 3
  6. property.node.children().joinToString() 具有上一项的对象符号
  7. property.delegate 为空
  8. 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


    【解决方案1】:

    正确的解决方案:

    fun getTypeName(parameter: KtCallableDeclaration): String? {
            return parameter.createTypeBindingForReturnType(bindingContext)
                ?.type
                ?.getJetTypeFqName(false)
        }
    

    布尔类型至少有以下值:kotlin.Boolean 和 java.lang.Boolean

    完整的code is here。

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2021-08-02
      相关资源
      最近更新 更多