内容
1.自定义注解
2.注解的生命周期
3.实战,反射创建对象
一.自定义注解
//自定义标识
//通过注解Annotation来实现标识的功能
//kotlin的注解完全继承于Java
//注解只是一个标识,不会影响类的运行
//给类做标识
@Target(AnnotationTarget.CLASS)
annotation class TableName
//给构造方法做标识
@Target(AnnotationTarget.CONSTRUCTOR)
annotation class MYCons
//给属性做标识
@Target(AnnotationTarget.PROPERTY)
annotation class MyParam
//给方法做标识
@Target(AnnotationTarget.FUNCTION)
annotation class MyFunc
//给参数做标识
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class MyFuncParam
@TableName class TTTT @MYCons constructor(@MyParam var age: Int){
@MyParam val name: String = "jack"
@MYCons constructor(@MyFuncParam name: String): this(20){
}
@MyFunc fun show(@MyFuncParam des: String){
}
}
二.注解的生命周期
//给类做标识
//注解的 作用域/生命周期
@Retention(AnnotationRetention.RUNTIME)//源代码阶段(SOURCE),字节码文件(BINARY),运行阶段(RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class TableName(val name: String)//TTTT -> TTTTTable
@TableName(name = "TTTTTable") class TTTT constructor( var age: Int){
val name: String = "jack"
constructor(name: String): this(20){
}
fun show(des: String){
}
}
三.实战,反射创建对象
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.primaryConstructor
//创建两个类
class Student
@Entity class User(
@ColumnInfo var id: Int,
@ColumnInfo var name: String,
@ColumnInfo var icon: String
)
//类注解
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class Entity
//属性注解
@Retention
@Target(AnnotationTarget.PROPERTY)
annotation class ColumnInfo
fun selectData(): Map<String,Map<String,Any>>{
//模拟有两个表 User Student
//使用Map封装数据
val userData = mapOf(
Pair("id",1),
Pair("name","jack"),
Pair("icon","www.baidu,.com")
)
val studentData = mapOf(
Pair("sId",1),
Pair("name","小王"),
Pair("address","西南大学")
)
val datas= mapOf(
Pair("User",userData),
Pair("Student",studentData)
)
return datas
}
fun autoParseFromTable(modelClz: KClass<out Any>): Any?{
//先从数据库里面读取出表对应的数据
val datas = selectData()
//判断传递过来的KClass对象有没有Entity注解
val entity = modelClz.findAnnotation<Entity>()
if(entity == null){
//传递过来的类,没有Entity标识
//即不能自动转化
return null
}else{
//这个类可以被自动转化
//获取 类名---表名
val tableName = modelClz.simpleName
//使用这个表名去数据中获取这个表对应的数据
val info = datas[tableName]
//创建对象,再将info的数据对应地填充到对象的属性中
//使用默认的主构造函数创建
val constructor = modelClz.primaryConstructor
//创建一个数组,保存解析的属性的值
//创建的数组元素个数 和 构造函数中参数的个数相同
val params = arrayOfNulls<Any>(constructor?.parameters?.size!!)
//遍历构造函数的参数
constructor.parameters.forEach{
//获取参数名
//从数据源中获取这个参数对应的值
val value = info?.get(it.name)
//将这个值保存到数组中
params[it.index] = value
}
//调用构造函数创建对象
val obj = constructor?.call(*params)
return obj
}
}
/*//vararg对应的是Array类型的数组,不是List
fun show(vararg e: Int){
e.forEach { println(it) }
}*/
fun main(){
val user = autoParseFromTable(User::class) as User
println(user)
//输出 User@212bf671
/*val temp = arrayOf(10,20,30).toIntArray()
show(*temp)*/
}
这篇博客详细介绍了Kotlin中的自定义注解及其生命周期,并通过实例展示了如何利用反射来创建对象,适合Kotlin初学者进阶学习。

被折叠的 条评论
为什么被折叠?



