为什么说java反射慢

==反射通常包括几两步:==

  • 通过类名、类加载器查找类定义

  • 通过类定义创建实例、访问方法、字段

对于第一点,我们很容易想到办法

  • 缓存类定义,也就是类名对应的Class

对于第二点,需要深究

  • 常见耗时,通过Class访问时。大概是普通方式的1.5-3(不准确)倍

  • The flexibility achieved by reflection in Java is attained to a large extent by delaying the binding of names. That is, the binding of names (of methods, fields, and
    so on) that is normally done by the compiler is delayed until runtime. This
    delayed binding has a performance impactin the form of searches and checks
    executed at runtime. As an example of the former, getMethodmust search the
    inheritance hierarchy for the appropriate method object. An example of the latter is Method.invoke, which must check accessibility. This is not a negative statement; it is merely an observation of the trade-off involved in the use of reflection.

参考:

java reflect in action