大家都说 Java 反射效率低,你知道原因在哪里么

梦里梦外; 2021-06-10 20:39 711阅读 0赞

预备知识

  1. 了解 Java 反射基本用法

看完本文可以达到什么程度

  1. 了解 Java 反射原理及 Java 反射效率低的原因

文章概览

summary

我们在 Java 开发中,难免会接触到反射,而在一些框架中,反射的运用更是常见。我相信,每次提到反射,大家的第一反应一定是反射效率低,尽量少使用。
但是反射的效率到底低多少?反射效率低的原因在哪里?
这篇文章就来探索一下这些问题。
由于本机上安装的是 openjdk 12,所以这里就使用 openjdk 12 源码进行分析。

我们先看结论,然后分析一下 Java 反射的原理,过程中大家可以根据结论,对源码做一些思考,然后再根据原理中的一些实现,看看 Java 反射效率低的原因。

零、先放结论

Java 反射效率低主要原因是:

  1. Method#invoke 方法会对参数做封装和解封操作
  2. 需要检查方法可见性
  3. 需要校验参数
  4. 反射方法难以内联
  5. JIT 无法优化

一、Java 反射原理—获取要反射的方法

1.1 反射的使用

我们先来看看 Java 反射使用的一段代码:

  1. public class RefTest {
  2. public static void main(String[] args) {
  3. try {
  4. Class clazz = Class.forName("com.zy.java.RefTest");
  5. Object refTest = clazz.newInstance();
  6. Method method = clazz.getDeclaredMethod("refMethod");
  7. method.invoke(refTest);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. public void refMethod() {
  13. }
  14. }
  15. 复制代码

我们在调用反射时,首先会创建 Class 对象,然后获取其 Method 对象,调用 invoke 方法。
获取反射方法时,有两个方法,getMethodgetDeclaredMethod,我们就从这两个方法开始,一步步看下反射的原理。
接下来就进入代码分析,大家做好准备。

1.2 getMethod / getDeclaredMethod

这里我们先整体看一下 getMethod 和 getDeclaredMethod 的实现。

  1. class Class {
  2. @CallerSensitive
  3. public Method getMethod(String name, Class<?>... parameterTypes)
  4. throws NoSuchMethodException, SecurityException {
  5. Objects.requireNonNull(name);
  6. SecurityManager sm = System.getSecurityManager();
  7. if (sm != null) {
  8. // 1. 检查方法权限
  9. checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
  10. }
  11. // 2. 获取方法
  12. Method method = getMethod0(name, parameterTypes);
  13. if (method == null) {
  14. throw new NoSuchMethodException(methodToString(name, parameterTypes));
  15. }
  16. // 3. 返回方法的拷贝
  17. return getReflectionFactory().copyMethod(method);
  18. }
  19. @CallerSensitive
  20. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  21. throws NoSuchMethodException, SecurityException {
  22. Objects.requireNonNull(name);
  23. SecurityManager sm = System.getSecurityManager();
  24. if (sm != null) {
  25. // 1. 检查方法是权限
  26. checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
  27. }
  28. // 2. 获取方法
  29. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  30. if (method == null) {
  31. throw new NoSuchMethodException(methodToString(name, parameterTypes));
  32. }
  33. // 3. 返回方法的拷贝
  34. return getReflectionFactory().copyMethod(method);
  35. }
  36. }
  37. 复制代码

从上面的代码,我们可以看到,获取方法的流程分三步走:

  1. 检查方法权限
  2. 获取方法 Method 对象
  3. 返回方法的拷贝

这里主要有两个区别:

  1. getMethod 中 checkMemberAccess 传入的是 Member.PUBLIC,而 getDeclaredMethod 传入的是 Member.DECLARED 这两个值有什么区别呢?我们看下代码中的注释:

    interface Member {

    1. /**
    2. * Identifies the set of all public members of a class or interface,
    3. * including inherited members.
    4. */
    5. public static final int PUBLIC = 0;
    6. /**
    7. * Identifies the set of declared members of a class or interface.
    8. * Inherited members are not included.
    9. */
    10. public static final int DECLARED = 1;

    }
    复制代码

注释里清楚的解释了 PUBLIC 和 DECLARED 的不同,PUBLIC 会包括所有的 public 方法,包括父类的方法,而 DECLARED 会包括所有自己定义的方法,public,protected,private 都在此,但是不包括父类的方法。
这也正是 getMethod 和 getDeclaredMethod 的区别。

  1. getMethod 中获取方法调用的是 getMethod0,而 getDeclaredMethod 获取方法调用的是 privateGetDeclaredMethods 关于这个区别,这里简单提及一下,后面具体分析代码。
    privateGetDeclaredMethods 是获取类自身定义的方法,参数是 boolean publicOnly,表示是否只获取公共方法。

    private Method[] privateGetDeclaredMethods(boolean publicOnly) {

    1. //...

    }
    复制代码

而 getMethod0 会递归查找父类的方法,其中会调用到 privateGetDeclaredMethods 方法。

既然我们上面看了 getMethod 和 getDeclaredMethod 的区别,我们自然选择 getMethod 方法进行分析,这样可以走到整个流程。

1.3 getMethod 方法

getMethod 方法流程如下图:

getMethod

  1. class Class {
  2. public Method getMethod(String name, Class<?>... parameterTypes)
  3. throws NoSuchMethodException, SecurityException {
  4. Objects.requireNonNull(name);
  5. SecurityManager sm = System.getSecurityManager();
  6. if (sm != null) {
  7. // 1. 检查方法权限
  8. checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
  9. }
  10. // 2. 获取方法 Method 对象
  11. Method method = getMethod0(name, parameterTypes);
  12. if (method == null) {
  13. throw new NoSuchMethodException(methodToString(name, parameterTypes));
  14. }
  15. // 3. 返回方法拷贝
  16. return getReflectionFactory().copyMethod(method);
  17. }
  18. }
  19. 复制代码

我们上面说到获取方法分三步走:

  1. 检查方法权限
  2. 获取方法 Method 对象
  3. 返回方法的拷贝

我们先看看检查方法权限做了些什么事情。

1.3.1 checkMemberAccess

  1. class Class {
  2. private void checkMemberAccess(SecurityManager sm, int which,
  3. Class<?> caller, boolean checkProxyInterfaces) {
  4. /* Default policy allows access to all {@link Member#PUBLIC} members,
  5. * as well as access to classes that have the same class loader as the caller.
  6. * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
  7. * permission.
  8. */
  9. final ClassLoader ccl = ClassLoader.getClassLoader(caller);
  10. if (which != Member.PUBLIC) {
  11. final ClassLoader cl = getClassLoader0();
  12. if (ccl != cl) {
  13. sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
  14. }
  15. }
  16. this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
  17. }
  18. }
  19. 复制代码

在这里可以看到,对于非 Member.PUBLIC 的访问,会增加一项检测,SecurityManager.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 这项检测需要运行时申请 RuntimePermission("accessDeclaredMembers")
这里就不继续往下看了,方法整体是在检查是否可以访问对象成员。

接着看下是如何获取方法的 Method 对象。

1.3.2 getMethod0

  1. class Class {
  2. private Method getMethod0(String name, Class<?>[] parameterTypes) {
  3. PublicMethods.MethodList res = getMethodsRecursive(
  4. name,
  5. parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
  6. /* includeStatic */ true);
  7. return res == null ? null : res.getMostSpecific();
  8. }
  9. }
  10. 复制代码

这里是通过 getMethodsRecursive 获取到 MethodList 对象,然后通过 MethodList#getMostSpecific 方法筛选出对应的方法。 MethodList#getMOstSpecific 会筛选返回值类型最为具体的方法,至于为什么会有返回值的区别,后面会讲到。
(这里的具体,指的是有两个方法,返回值分别是 Child 和 Parent,Child 继承自 Parent,这里会筛选出返回值为 Child 的方法)。

接着看 getMethodsRecursive 方法,是如何获取方法的。

1.3.3 getMethodsRecursive

  1. class Class {
  2. private PublicMethods.MethodList getMethodsRecursive(String name,
  3. Class<?>[] parameterTypes,
  4. boolean includeStatic) {
  5. // 1. 获取自己的 public 方法
  6. Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
  7. // 2. 筛选符合条件的方法,构造 MethodList 对象
  8. PublicMethods.MethodList res = PublicMethods.MethodList
  9. .filter(methods, name, parameterTypes, includeStatic);
  10. // 找到方法,直接返回
  11. if (res != null) {
  12. return res;
  13. }
  14. // 3. 没有找到方法,就获取其父类,递归调用 getMethodsRecursive 方法
  15. Class<?> sc = getSuperclass();
  16. if (sc != null) {
  17. res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
  18. }
  19. // 4. 获取接口中对应的方法
  20. for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
  21. res = PublicMethods.MethodList.merge(
  22. res, intf.getMethodsRecursive(name, parameterTypes,
  23. /* includeStatic */ false));
  24. }
  25. return res;
  26. }
  27. }
  28. 复制代码

这里获取方法有四个步骤:

  1. 通过 privateGetDeclaredMethods 获取自己所有的 public 方法
  2. 通过 MethodList#filter 查找 方法名,参数相同的方法,如果找到,直接返回
  3. 如果自己没有实现对应的方法,就去父类中查找对应的方法
  4. 查找接口中对应的方法

通过上面四个步骤,最终获取到的是一个 MethodList 对象,是一个链表结点,其 next 指向下一个结点。也就是说,这里获取到的 Method 会有多个。
这里稍微解释一下,在我们平时编写 Java 代码时,同一个类是不能有方法名和方法参数都相同的方法的,而实际上,在 JVM 中,一个方法签名是和 返回值,方法名,方法参数 三者相关的。 也就是说,在 JVM 中,可以存在 方法名和方法参数都相同,但是返回值不同的方法。
所以这里返回的是一个方法链表。
所以上面最终返回方法时会通过 MethodList#getMostSpecific 进行返回值的筛选,筛选出返回值类型最具体的方法。

这里我们先暂停回顾一下整体的调用链路:

  1. getMethod -> getMethod0 -> getMethodsRecursive -> privateGetDeclaredMethods
  2. 复制代码

通过函数调用,最终会调用到 privateGetDeclaredMethods 方法,也就是真正获取方法的地方。

1.3.4 privateGetDeclaredMethods

  1. class Class {
  2. private Method[] privateGetDeclaredMethods(boolean publicOnly) {
  3. Method[] res;
  4. // 1. 通过缓存获取 Method[]
  5. ReflectionData<T> rd = reflectionData();
  6. if (rd != null) {
  7. res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
  8. if (res != null) return res;
  9. }
  10. // 2. 没有缓存,通过 JVM 获取
  11. res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
  12. if (rd != null) {
  13. if (publicOnly) {
  14. rd.declaredPublicMethods = res;
  15. } else {
  16. rd.declaredMethods = res;
  17. }
  18. }
  19. return res;
  20. }
  21. }
  22. 复制代码

在 privateGetDeclaredMethods 获取方法时,有两个步骤:

  1. relectionData 通过缓存获取
  2. 如果缓存没有命中的话,通过 getDeclaredMethods0 获取方法

先看看 relectionData 方法:

  1. class Class {
  2. private ReflectionData<T> reflectionData() {
  3. SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
  4. int classRedefinedCount = this.classRedefinedCount;
  5. ReflectionData<T> rd;
  6. if (reflectionData != null &&
  7. (rd = reflectionData.get()) != null &&
  8. rd.redefinedCount == classRedefinedCount) {
  9. return rd;
  10. }
  11. // else no SoftReference or cleared SoftReference or stale ReflectionData
  12. // -> create and replace new instance
  13. return newReflectionData(reflectionData, classRedefinedCount);
  14. }
  15. }
  16. 复制代码

在 Class 中会维护一个 ReflectionData 的软引用,作为反射数据的缓存。
ReflectionData 结构如下:

  1. private static class ReflectionData<T> {
  2. volatile Field[] declaredFields;
  3. volatile Field[] publicFields;
  4. volatile Method[] declaredMethods;
  5. volatile Method[] publicMethods;
  6. volatile Constructor<T>[] declaredConstructors;
  7. volatile Constructor<T>[] publicConstructors;
  8. // Intermediate results for getFields and getMethods
  9. volatile Field[] declaredPublicFields;
  10. volatile Method[] declaredPublicMethods;
  11. volatile Class<?>[] interfaces;
  12. // Cached names
  13. String simpleName;
  14. String canonicalName;
  15. static final String NULL_SENTINEL = new String();
  16. // Value of classRedefinedCount when we created this ReflectionData instance
  17. final int redefinedCount;
  18. }
  19. 复制代码

可以看到,保存了 Class 中的属性和方法。 如果缓存为空,就会通过 getDeclaredMethods0 从 JVM 中查找方法。
getDeclaredMethods0 是一个 native 方法,这里暂时先不看。

通过上面几个步骤,就获取到 Method 数组。

这就是 getMethod 方法的整个实现了。
我们再回过头看一下 getDeclaredMethod 方法的实现,通过 privateGetDeclaredMethods 获取方法以后,会通过 searchMethods 对方法进行筛选。

  1. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  2. throws NoSuchMethodException, SecurityException {
  3. // ...
  4. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  5. // ...
  6. }
  7. 复制代码

searchMethods 方法实现比较简单,就是对比方法名,参数,方法返回值。

  1. class Class {
  2. private static Method searchMethods(Method[] methods,
  3. String name,
  4. Class<?>[] parameterTypes)
  5. {
  6. ReflectionFactory fact = getReflectionFactory();
  7. Method res = null;
  8. for (Method m : methods) {
  9. // 比较方法名
  10. if (m.getName().equals(name)
  11. // 比较方法参数
  12. && arrayContentsEq(parameterTypes,
  13. fact.getExecutableSharedParameterTypes(m))
  14. // 比较返回值
  15. && (res == null
  16. || (res.getReturnType() != m.getReturnType()
  17. && res.getReturnType().isAssignableFrom(m.getReturnType()))))
  18. res = m;
  19. }
  20. return res;
  21. }
  22. }
  23. 复制代码

1.3.5 Method#copy

在获取到对应方法以后,并不会直接返回,而是会通过 getReflectionFactory().copyMethod(method); 返回方法的一个拷贝。
最终调用的是 Method#copy,我们来看看其实现。

  1. class Method {
  2. Method copy() {
  3. // This routine enables sharing of MethodAccessor objects
  4. // among Method objects which refer to the same underlying
  5. // method in the VM. (All of this contortion is only necessary
  6. // because of the "accessibility" bit in AccessibleObject,
  7. // which implicitly requires that new java.lang.reflect
  8. // objects be fabricated for each reflective call on Class
  9. // objects.)
  10. if (this.root != null)
  11. throw new IllegalArgumentException("Can not copy a non-root Method");
  12. Method res = new Method(clazz, name, parameterTypes, returnType,
  13. exceptionTypes, modifiers, slot, signature,
  14. annotations, parameterAnnotations, annotationDefault);
  15. res.root = this;
  16. // Might as well eagerly propagate this if already present
  17. res.methodAccessor = methodAccessor;
  18. return res;
  19. }
  20. }
  21. 复制代码

会 new 一个 Method 实例并返回。
这里有两点要注意:

  1. 设置 root = this
  2. 会给 Method 设置 MethodAccessor,用于后面方法调用。也就是所有的 Method 的拷贝都会使用同一份 methodAccessor。

通过上面的步骤,就获取到了需要反射的方法。
我们再回顾一下之前的流程。

getMethod

二、Java 反射原理—调用反射方法

获取到方法以后,通过 Method#invoke 调用方法。

  1. class Method {
  2. public Object invoke(Object obj, Object... args)
  3. throws IllegalAccessException, IllegalArgumentException,
  4. InvocationTargetException
  5. {
  6. if (!override) {
  7. Class<?> caller = Reflection.getCallerClass();
  8. // 1. 检查权限
  9. checkAccess(caller, clazz,
  10. Modifier.isStatic(modifiers) ? null : obj.getClass(),
  11. modifiers);
  12. }
  13. // 2. 获取 MethodAccessor
  14. MethodAccessor ma = methodAccessor; // read volatile
  15. if (ma == null) {
  16. // 创建 MethodAccessor
  17. ma = acquireMethodAccessor();
  18. }
  19. // 3. 调用 MethodAccessor.invoke
  20. return ma.invoke(obj, args);
  21. }
  22. }
  23. 复制代码

invoke 方法的实现,分为三步:

2.1 检查是否有权限调用方法

这里对 override 变量进行判断,如果 override == true,就跳过检查 我们通常在 Method#invoke 之前,会调用 Method#setAccessible(true),就是设置 override 值为 true。

2.2 获取 MethodAccessor

在上面获取 Method 的时候我们讲到过,Method#copy 会给 Method 的 methodAccessor 赋值。所以这里的 methodAccessor 就是拷贝时使用的 MethodAccessor。
如果 ma 为空,就去创建 MethodAccessor。

  1. class Method {
  2. private MethodAccessor acquireMethodAccessor() {
  3. // First check to see if one has been created yet, and take it
  4. // if so
  5. MethodAccessor tmp = null;
  6. if (root != null) tmp = root.getMethodAccessor();
  7. if (tmp != null) {
  8. methodAccessor = tmp;
  9. } else {
  10. // Otherwise fabricate one and propagate it up to the root
  11. tmp = reflectionFactory.newMethodAccessor(this);
  12. setMethodAccessor(tmp);
  13. }
  14. return tmp;
  15. }
  16. }
  17. 复制代码

这里会先查找 root 的 MethodAccessor,这里的 root 在上面 Method#copy 中设置过。
如果还是没有找到,就去创建 MethodAccessor。

  1. class ReflectionFactory {
  2. public MethodAccessor newMethodAccessor(Method method) {
  3. // 其中会对 noInflation 进行赋值
  4. checkInitted();
  5. // ...
  6. if (noInflation && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
  7. // 生成的是 MethodAccessorImpl
  8. return new MethodAccessorGenerator().
  9. generateMethod(method.getDeclaringClass(),
  10. method.getName(),
  11. method.getParameterTypes(),
  12. method.getReturnType(),
  13. method.getExceptionTypes(),
  14. method.getModifiers());
  15. } else {
  16. NativeMethodAccessorImpl acc =
  17. new NativeMethodAccessorImpl(method);
  18. DelegatingMethodAccessorImpl res =
  19. new DelegatingMethodAccessorImpl(acc);
  20. acc.setParent(res);
  21. return res;
  22. }
  23. }
  24. }
  25. 复制代码

这里可以看到,一共有三种 MethodAccessor。MethodAccessorImplNativeMethodAccessorImplDelegatingMethodAccessorImpl
采用哪种 MethodAccessor 根据 noInflation 进行判断,noInflation 默认值为 false,只有指定了 sun.reflect.noInflation 属性为 true,才会 采用 MethodAccessorImpl。
所以默认会调用 NativeMethodAccessorImpl。

MethodAccessorImpl 是通过动态生成字节码来进行方法调用的,是 Java 版本的 MethodAccessor,字节码生成比较复杂,这里不放代码了。大家感兴趣可以看这里的 generate 方法。

DelegatingMethodAccessorImpl 就是单纯的代理,真正的实现还是 NativeMethodAccessorImpl。

  1. class DelegatingMethodAccessorImpl extends MethodAccessorImpl {
  2. private MethodAccessorImpl delegate;
  3. DelegatingMethodAccessorImpl(MethodAccessorImpl delegate) {
  4. setDelegate(delegate);
  5. }
  6. public Object invoke(Object obj, Object[] args)
  7. throws IllegalArgumentException, InvocationTargetException
  8. {
  9. return delegate.invoke(obj, args);
  10. }
  11. void setDelegate(MethodAccessorImpl delegate) {
  12. this.delegate = delegate;
  13. }
  14. }
  15. 复制代码

NativeMethodAccessorImpl 是 Native 版本的 MethodAccessor 实现。

  1. class NativeMethodAccessorImpl extends MethodAccessorImpl {
  2. public Object invoke(Object obj, Object[] args)
  3. throws IllegalArgumentException, InvocationTargetException
  4. {
  5. // We can't inflate methods belonging to vm-anonymous classes because
  6. // that kind of class can't be referred to by name, hence can't be
  7. // found from the generated bytecode.
  8. if (++numInvocations > ReflectionFactory.inflationThreshold()
  9. && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
  10. // Java 版本的 MethodAccessor
  11. MethodAccessorImpl acc = (MethodAccessorImpl)
  12. new MethodAccessorGenerator().
  13. generateMethod(method.getDeclaringClass(),
  14. method.getName(),
  15. method.getParameterTypes(),
  16. method.getReturnType(),
  17. method.getExceptionTypes(),
  18. method.getModifiers());
  19. parent.setDelegate(acc);
  20. }
  21. // Native 版本调用
  22. return invoke0(method, obj, args);
  23. }
  24. private static native Object invoke0(Method m, Object obj, Object[] args);
  25. }
  26. 复制代码

在 NativeMethodAccessorImpl 的实现中,我们可以看到,有一个 numInvocations 阀值控制,numInvocations 表示调用次数。如果 numInvocations 大于 15(默认阀值是 15),那么就使用 Java 版本的 MethodAccessorImpl。

为什么采用这个策略呢,可以 JDK 中的注释:

  1. // "Inflation" mechanism. Loading bytecodes to implement
  2. // Method.invoke() and Constructor.newInstance() currently costs
  3. // 3-4x more than an invocation via native code for the first
  4. // invocation (though subsequent invocations have been benchmarked
  5. // to be over 20x faster). Unfortunately this cost increases
  6. // startup time for certain applications that use reflection
  7. // intensively (but only once per class) to bootstrap themselves.
  8. // To avoid this penalty we reuse the existing JVM entry points
  9. // for the first few invocations of Methods and Constructors and
  10. // then switch to the bytecode-based implementations.
  11. //
  12. // Package-private to be accessible to NativeMethodAccessorImpl
  13. // and NativeConstructorAccessorImpl
  14. private static boolean noInflation = false;
  15. 复制代码

Java 版本的 MethodAccessorImpl 调用效率比 Native 版本要快 20 倍以上,但是 Java 版本加载时要比 Native 多消耗 3-4 倍资源,所以默认会调用 Native 版本,如果调用次数超过 15 次以后,就会选择运行效率更高的 Java 版本。
那为什么 Native 版本运行效率会没有 Java 版本高呢?从 R 大博客来看,是因为 这是HotSpot的优化方式带来的性能特性,同时也是许多虚拟机的共同点:跨越native边界会对优化有阻碍作用,它就像个黑箱一样让虚拟机难以分析也将其内联,于是运行时间长了之后反而是托管版本的代码更快些

2.3 调用 MethodAccessor#invoke 实现方法的调用

在生成 MethodAccessor 以后,就调用其 invoke 方法进行最终的反射调用。
这里我们对 Java 版本的 MethodAccessorImpl 做个简单的分析,Native 版本暂时不做分析。
在前面我们提到过 MethodAccessorImpl 是通过 MethodAccessorGenerator#generate 生成动态字节码然后动态加载到 JVM 中的。
其中生成 invoke 方法字节码的是 MethodAccessorGenerator#emitInvoke。
我们看其中校验参数的一小段代码:

  1. // Iterate through incoming actual parameters, ensuring that each
  2. // is compatible with the formal parameter type, and pushing the
  3. // actual on the operand stack (unboxing and widening if necessary).
  4. // num args of other invoke bytecodes
  5. for (int i = 0; i < parameterTypes.length; i++) {
  6. // ...
  7. if (isPrimitive(paramType)) {
  8. // Unboxing code.
  9. // Put parameter into temporary local variable
  10. // astore_3 | astore_2
  11. // ...
  12. // repeat for all possible widening conversions:
  13. // aload_3 | aload_2
  14. // instanceof <primitive boxing type>
  15. // ifeq <next unboxing label>
  16. // aload_3 | aload_2
  17. // checkcast <primitive boxing type> // Note: this is "redundant",
  18. // // but necessary for the verifier
  19. // invokevirtual <unboxing method>
  20. // <widening conversion bytecode, if necessary>
  21. // goto <next parameter label>
  22. // <next unboxing label:> ...
  23. // last unboxing label:
  24. // new <IllegalArgumentException>
  25. // dup
  26. // invokespecial <IllegalArgumentException ctor>
  27. // athrow
  28. }
  29. }
  30. 复制代码

通过上面的注释以及字节码,我们可以看到,生成的 invoke 方法,会对传入的参数做校验,其中会涉及到 unboxing 操作。

到此,基本上 Java 方法反射的原理就介绍完了。

三、Java 反射效率低的原因

了解了反射的原理以后,我们来分析一下反射效率低的原因。

  1. Method#invoke 方法会对参数做封装和解封操作

我们可以看到,invoke 方法的参数是 Object[] 类型,也就是说,如果方法参数是简单类型的话,需要在此转化成 Object 类型,例如 long ,在 javac compile 的时候 用了Long.valueOf() 转型,也就大量了生成了Long 的 Object, 同时 传入的参数是Object[]数值,那还需要额外封装object数组。
而在上面 MethodAccessorGenerator#emitInvoke 方法里我们看到,生成的字节码时,会把参数数组拆解开来,把参数恢复到没有被 Object[] 包装前的样子,同时还要对参数做校验,这里就涉及到了解封操作。
因此,在反射调用的时候,因为封装和解封,产生了额外的不必要的内存浪费,当调用次数达到一定量的时候,还会导致 GC。

  1. 需要检查方法可见性

通过上面的源码分析,我们会发现,反射时每次调用都必须检查方法的可见性(在 Method.invoke 里)

  1. 需要校验参数

反射时也必须检查每个实际参数与形式参数的类型匹配性(在NativeMethodAccessorImpl.invoke0 里或者生成的 Java 版 MethodAccessor.invoke 里);

  1. 反射方法难以内联

Method#invoke 就像是个独木桥一样,各处的反射调用都要挤过去,在调用点上收集到的类型信息就会很乱,影响内联程序的判断,使得 Method.invoke() 自身难以被内联到调用方。参见 www.iteye.com/blog/rednax…

  1. JIT 无法优化

在 JavaDoc 中提到:

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

因为反射涉及到动态加载的类型,所以无法进行优化。

总结

上面就是对反射原理和反射效率低的一些分析。

summary

参考资料

www.iteye.com/blog/rednax…

作者:ZYLAB
链接:https://juejin.im/post/5da33b2351882509334fc0d3
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发表评论

表情:
评论列表 (有 0 条评论,711人围观)

还没有评论,来说两句吧...

相关阅读