1. kotlin 定义注解
注解属性在使用时指定,其后不会再变,只能声明为只读属性
annotation class Annotation1(val name: String, val desc: String)
annotation class Annotation2(val field1: Int, val field2: String)
2. kotlin 元注解
- @Retention : 修饰注解可以保留多长时间 SOURCE, BINARY, RUNTIME
- @Target : 指定注解可以修饰的程序目标
- @Repeatable : 可重复修饰的注解
@Retention(value = AnnotationRetention.RUNTIME)
annotation class Annotation3()
@Target(AnnotationTarget.CLASS)
annotation class Annotation4()
@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class Annotation5()
@Target(AnnotationTarget.FUNCTION)
annotation class Annotation6()
@Target(AnnotationTarget.CONSTRUCTOR)
annotation class Annotation7()
@Target(AnnotationTarget.PROPERTY)
annotation class Annotation8()
@Target(AnnotationTarget.FIELD)
annotation class Annotation9()
@Target(AnnotationTarget.LOCAL_VARIABLE)
annotation class Annotation10()
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class Annotation11()
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.EXPRESSION)
annotation class Annotation12()
@Target(AnnotationTarget.TYPEALIAS)
annotation class Annotation13()
@Target(allowedTargets = [AnnotationTarget.CLASS, AnnotationTarget.FUNCTION])
annotation class Annotation14()
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
@Repeatable
annotation class RepeatAnnotation(val field1: Int, val field2: String)
class DemoAnnotation {
@RepeatAnnotation(1, "2")
@RepeatAnnotation(3, "4")
fun method() {
}
}
3. kotlin 使用注解
class TestAnnotation {
@Annotation1(name = "method", desc = "this is a normal method")
@Annotation2(field1 = 1001, field2 = "test annotation")
fun method() {
println("invoke method")
}
}
fun main() {
val annotationList = TestAnnotation::method.annotations
annotationList.forEach { annotation ->
if (annotation is Annotation1) {
println("name: ${annotation.name}, desc: ${annotation.desc}")
} else if (annotation is Annotation2) {
println("field1: ${annotation.field1}, field2: ${annotation.field2}")
}
}
}
附 Github 源码:
TestAnnotation.kt
|