在Kotlin / Java中,我们可以使用注解来标记一个有趣的属性。下面是一个示例:
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class InterestingProperty
class MyClass {
@InterestingProperty
val myProperty: String = "Hello, World!"
}
fun main() {
val myClass = MyClass()
val property = myClass::class.java.getDeclaredField("myProperty")
val annotation = property.getAnnotation(InterestingProperty::class.java)
if (annotation != null) {
println("myProperty is an interesting property!")
} else {
println("myProperty is not an interesting property.")
}
}
在上面的示例中,我们定义了一个名为InterestingProperty
的注解,该注解用于标记属性。然后,在MyClass
中,我们使用@InterestingProperty
将myProperty
属性标记为有趣的属性。
在main
函数中,我们使用反射获取myProperty
字段,并检查该字段上是否存在InterestingProperty
注解。如果存在该注解,则打印出消息"myProperty is an interesting property!",否则打印出消息"myProperty is not an interesting property."。
请注意,为了使注解在运行时可用,我们需要使用@Retention(AnnotationRetention.RUNTIME)
注解。
下一篇:标记元组的类型级操作