我正在尝试编写检查以防止返回带有特定注释的类型。
如,
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()
到目前为止我的规则如下
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
类型始终为空。是否有另一种获取注释的方法,或者我在这里犯了一些新手错误?:)
我的测试如下,
@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.")
}