kotlin注解应用

首先需要在app下引入扩展属性包,这样findAnnotation 扩展属性才生效

dependencies {
   ****
    implementation 'org.jetbrains.kotlin:kotlin-reflect:1.3.61'//反射
}

栗子:

package com.jdwx.opengl.kotlin

import kotlin.reflect.KClass
import kotlin.reflect.full.* //我们引入的包

@MustBeDocumented                                       // 1
@Target(AnnotationTarget.CLASS)                         // 2
@Retention(AnnotationRetention.RUNTIME)                 // 3
annotation class MyAnnotation(val description: String)  // 4


@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)                 // 1
@Target(
        AnnotationTarget.FUNCTION,
        AnnotationTarget.PROPERTY,
        AnnotationTarget.PROPERTY_GETTER,
        AnnotationTarget.PROPERTY_SETTER
)                                                       // 2
annotation class MemberAnnotation(val type: KClass<*> = Unit::class, val description: String)   // 3

@MyAnnotation(description = "这是一个测试类")  // 1
class Student {
    @MemberAnnotation(type = String::class, description = "名字") // 2
    @get:MemberAnnotation(type = String::class, description = "获得名字") // 3
    var name: String? = null
        private set

    @MemberAnnotation(type = Int::class, description = "年龄")    // 4
    @get:MemberAnnotation(type = Int::class, description = "获得年龄") // 5
    var age: Int = 0
        private set

    @MemberAnnotation(description = "设置姓名和年龄")  // 6
    fun setNameAndAge(name: String, age: Int) {
        this.name = name
        this.age = age
    }

    override fun toString(): String {
        return "Person [name=$name, age=$age]"
    }
}

fun main(args: Array<String>) {
    val clz = Student::class        // 1

    // 读取类注解
    val ann = clz.findAnnotation<MyAnnotation>()    // 2
    println("类${clz.simpleName},注解描述:${ann?.description ?: "无"}")   // 3

    // 读取成员函数的注解信息
    println("---------- 读取成员函数的注解信息 ----------")
    clz.declaredFunctions.forEach {     // 4
        val ann = it.findAnnotation<MemberAnnotation>()     // 5
        println("函数${it.name},注解描述:${ann?.description ?: "无"}")
    }

    // 读取属性的注解信息
    println("---------- 读取属性的注解信息 ----------")
    clz.declaredMemberProperties.forEach {      // 6
        val ann = it.findAnnotation<MemberAnnotation>()     // 7
        println("属性${it.name},注解描述:${ann?.description ?: "无"}")
    }
}

结果:

类Student,注解描述:这是一个测试类
———- 读取成员函数的注解信息 ———-
函数setNameAndAge,注解描述:设置姓名和年龄
函数toString,注解描述:无
———- 读取属性的注解信息 ———-
属性age,注解描述:年龄
属性name,注解描述:名字