我正在尝试在注释属性上放置注释。我的理解是,我应该可以通过代码访问它-但我不能。我想念什么?
package com.example.annotations
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import kotlin.reflect.full.findAnnotation
class AnnotationIssueTest {
@Test
fun testAnnotations() {
Assertions.assertNotNull(MyTestAnnotation::value.findAnnotation<PropertyMarker>())
}
@Test
fun testRegularClass() {
Assertions.assertNotNull(MyTestClass::value.findAnnotation<PropertyMarker>())
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class PropertyMarker
annotation class MyTestAnnotation(
@PropertyMarker val value: String
)
class MyTestClass(
@PropertyMarker val value: String
)
运行给定测试时,testAnnotations
失败,而testRegularClass
通过。这是错误还是我做错了什么?
答案 0 :(得分:2)
由于某些原因,注释属性的注释未进入字节码。但是,您可以改为注释属性获取器:
class AnnotationIssueTest {
@Test
fun testAnnotations() {
Assertions.assertNotNull(MyTestAnnotation::value.getter.findAnnotation<PropertyMarker>())
}
@Test
fun testRegularClass() {
Assertions.assertNotNull(MyTestClass::value.getter.findAnnotation<PropertyMarker>())
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY_GETTER)
annotation class PropertyMarker
annotation class MyTestAnnotation(
@get:PropertyMarker val value: String
)
class MyTestClass(
@get:PropertyMarker val value: String
)