//所有字段 val fields = cls.declaredMemberProperties for (field in fields){ //直接修改字段 val anno = field.findAnnotation<MyAnno>() if (anno != null){ @Suppress("UNCHECKED_CAST") val mutfield = field as KMutableProperty1<Any,Any> mutfield.isAccessible = true mutfield.set(myAnno,anno.value) } }
//调用set方法 val funcs = cls.functions for (func in funcs){ val anno = func.findAnnotation<MyAnno>() if (anno !=null){ func.call(myAnno,anno.value) } } }
还是和上次一样,我们的反射函数针对方法和属性进行注入,运行一下:
1 2 3 4 5 6 7 8
funmain() { val annoTest = AnnoTest() reflect(annoTest) println(annoTest) }
// out AnnoTest(name='testtttttt', mail='testtttttt2222')
成功注入!
对比
既然两个反射都能用,两个都是编译成jvm字节码了,那么试试在Java里读取下注解:
1 2 3 4 5 6 7 8 9 10 11
funmain() { val annoTest = AnnoTest() val cls = annoTest::class.java val fields = cls.fields for (field in fields){ val anno =field.getAnnotation(MyAnno::class.java) if (anno!=null){ println(anno.value) } } }
运行之后没有输出,我们的注解没有被读到。怎么回事呢。
试试读出所有的注解:
1 2 3 4 5 6 7 8 9 10 11
funmain() { val annoTest = AnnoTest() val cls = annoTest::class.java val fields = cls.fields for (field in fields){ val annos =field.annotations for (anno in annos){ println(anno) } } }
还是没有输出,看来我们的 字段上根本没有注解,试试读取方法的注解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funmain(){ val annoTest = AnnoTest()
val cls = annoTest::class.java val fields = cls.declaredMethods for (field in fields){ val annos =field.annotations for (anno in annos){ println(anno) } } } // out @MyAnno("testtttttt") @MyAnno("testtttttt2222")