首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Detekt返回类型注释始终为空

Detekt返回类型注释始终为空
EN

Stack Overflow用户
提问于 2021-04-15 08:21:15
回答 1查看 248关注 0票数 2

我正在尝试编写一个检查,以防止返回带有特定注释的Type。

比如,

代码语言:javascript
复制
const val TEST_CONTENT = 
        """
        | package sample.test
        |
        | @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS)
        | annotation class SampleAnnotation
        | 
        | @SampleAnnotation
        | internal interface ConditionalReturnedType 
        |
        | interface TestCase {
        |   // this is not allowed
        |   fun someFunction(whatever: String): ConditionalReturnedType
        | }
        """.trimIndent()

到目前为止,我的规则如下

代码语言:javascript
复制
override fun visitNamedFunction(function: KtNamedFunction) {
    super.visitNamedFunction(function)
    if (BindingContext.EMPTY == bindingContext) {
      return
    }

    val returnType = function.createTypeBindingForReturnType(bindingContext)?.type ?: return

    // HERE Annotations is always EMPTY
    val annotations = returnType.annotations
    val hasRequiredAnnotation = annotations.hasAnnotation(FqName("SampleAnnotation"))
    if (!hasRequiredAnnotation) return

    if (isAnAllowedCondition(function, returnType)) {
      // Allow returning the type for this condition
      return
    }

    report(CodeSmell(/** */))
  }

我可以验证returnType是正确的,但是类型的annotations总是空的。是否有一种获得注释的替代方法,还是我在这里做了一些新手错误?)

我的测试如下,

代码语言:javascript
复制
@Test
fun `negative cuz it doesnt match allowed conditions`() {
  val actual = subject.compileAndLintWithContext(ENVIRONMENT.env, TEST_CONTENT)
  assertThat(actual).hasSize(1)
  assertThat(actual[0].message)
      .isEqualTo("Ops. You shouldn't return that.")
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-23 12:46:51

因此,有两个问题。

  1. --我在那里添加了visitClass并检查了注释,它始终是空的--这很奇怪,让我意识到问题在于测试。出于某种原因,使用|的代码块使注释行在编译时被删除。| @SampleAnnotation --这在编译后的文件中根本不存在。删除|解决了这个问题。由于某种原因,
  2. 看起来不像是在KotlinType for returnType中填充了注释字段。因此,我需要以某种方式到达KtClass对象,添加以下内容,我得到了注释.

代码语言:javascript
复制
val returnType = function.createTypeBindingForReturnType(bindingContext)?.type ?: return
val annotations = returnType.constructor.declarationDescriptor?.annotations ?: return
val isAnnotated = annotations.any { it.type.toString() == "SampleAnnotation" }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67104775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档