//所有字段 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) } } }
long start = System.currentTimeMillis(); AnnoTest annotest = new AnnoTest(); for (int i = 0; i < 100000000; i++) { reflect(annotest); } long time = System.currentTimeMillis()-start; System.out.println(annotest); System.out.println(time); } // out AnnoTest{name='testtttttt'} 41898
用时41秒
再看Kotlin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funmain() = runBlocking { val annoTest = AnnoTest()
val timeInMillis = measureTimeMillis { //这写法比Java方便一万倍有没有 for (i in1..100000000){ reflect(annoTest) } }
println(annoTest) println(timeInMillis) } // out AnnoTest(name='testtttttt') 20885