我试图在注释属性上放置注释。我的理解是我应该能够在代码中访问它 - 但我无法做到。我错过了什么?
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
通过时失败。这是一个错误还是我做错了什么?
由于某种原因,注释属性的注释不会进入字节码。但是,您可以注释属性getter:
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
)