您的位置:首页 > 编程语言 > Java开发

Java 反射 浅尝

2013-04-25 00:00 197 查看
getMethod 反射效率低?缓存?

经过查阅相关资料,首先要区别getDeclaredMethod 和getMethod的区别:

getDeclaredMethod(String name, Class... parameterTypes)
Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

getMethod(String name, Class... parameterTypes)
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
由此可见,getDeclaredMethod*()获取的是类自身声明的

所有方法,包含public、protected和private方法。getMethod*()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。

其次。在效率上来说,反射相比直接调用性能上还是相差很多的,通过简单测试将近差30多倍,这个当然是合理的。在使用反射的时候,尽量同一方法采用静态类来进行缓存,并且在invoke之前设置setAccessible为true,这样就免去了安全性检查的过程,性能上会优化很多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 反射