我正在尝试编写一个检查,以防止返回带有特定注释的Type。
比如,
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.")
}发布于 2021-04-23 12:46:51
因此,有两个问题。
visitClass并检查了注释,它始终是空的--这很奇怪,让我意识到问题在于测试。出于某种原因,使用|的代码块使注释行在编译时被删除。| @SampleAnnotation --这在编译后的文件中根本不存在。删除|解决了这个问题。由于某种原因,KotlinType for returnType中填充了注释字段。因此,我需要以某种方式到达KtClass对象,添加以下内容,我得到了注释.val returnType = function.createTypeBindingForReturnType(bindingContext)?.type ?: return
val annotations = returnType.constructor.declarationDescriptor?.annotations ?: return
val isAnnotated = annotations.any { it.type.toString() == "SampleAnnotation" }https://stackoverflow.com/questions/67104775
复制相似问题