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,这样就免去了安全性检查的过程,性能上会优化很多。
经过查阅相关资料,首先要区别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高新技术—反射
- java反射详解
- java 反射机制实例。
- Java反射技术一:基本知识点
- Java高新技术第二篇:反射技术
- (Java 基础知识) Java反射
- Java使用反射来获取泛型信息
- Java反射
- Java反射详解
- java 反射机制-学习笔记(5)
- Java反射
- JAVA进阶学习-反射机制
- Java基础----反射Reflect----Constructor
- Java基础---Java---基础加强---内省的简单运用、注解的定义与反射调用、 自定义注解及其应用、泛型及泛型的高级应用、泛型集合的综合
- Java反射
- 细说反射,Java 和 Android 开发者必须跨越的坎
- JAVA基础(12) java代码反射获取log
- 【转】JAVA的内省(introspector)与反射(reflection)
- java 反射机制 Demo 练习
- java反射遍历实体类属性和类型,并赋值和获取值