反射是java的一个特性,这一特性也使得它给了广大的第三方框架和开发过者很大的想像空间。

  通过反射,java可以动态的加载未知的外部配置对象,临时生成字节码进行加载使用,从而使代码更灵活!可以极大地提高应用的扩展性!

  但是,除了停留在使用其华丽功能,我们还可以去看看其实现!

主要看两个方法的使用:

来个例子!

  1. public class HelloReflect {
  2. public static void main(String[] args) {
  3. try {
  4. // 1. 使用外部配置的实现,进行动态加载类
  5. TempFunctionTest test = (TempFunctionTest)Class.forName("com.tester.HelloReflect").newInstance();
  6. test.sayHello("call directly");
  7. // 2. 根据配置的函数名,进行方法调用(不需要通用的接口抽象)
  8. Object t2 = new TempFunctionTest();
  9. Method method = t2.getClass().getDeclaredMethod("sayHello", String.class);
  10. method.invoke(test, "method invoke");
  11. } catch (ClassNotFoundException e) {
  12. e.printStackTrace();
  13. } catch (InstantiationException e) {
  14. e.printStackTrace();
  15. } catch (IllegalAccessException e) {
  16. e.printStackTrace();
  17. } catch (NoSuchMethodException e ) {
  18. e.printStackTrace();
  19. } catch (InvocationTargetException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23.  
  24. public void sayHello(String word) {
  25. System.out.println("hello," + word);
  26. }
  27.  
  28. }

  运行结果显而易见!我们来看执行流程!

1. 反射获取类实例 Class.forName("C.a.xxx");

  首先调用了 java.lang.Class 的静态方法,获取类信息!

  1. @CallerSensitive
  2. public static Class<?> forName(String className)
  3. throws ClassNotFoundException {
  4. // 先通过反射,获取调用进来的类信息,从而获取当前的 classLoader
  5. Class<?> caller = Reflection.getCallerClass();
  6. // 调用native方法进行获取class信息
  7. return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
  8. }

  forName()反射获取类信息,并没有将实现留给了java,而是交给了jvm去加载!

  主要是先获取 ClassLoader, 然后调用 native 方法,获取信息,加载类则是回调 java.lang.ClassLoader.

  最后,jvm又会回调 ClassLoader 进类加载!

  1. //
  2. public Class<?> loadClass(String name) throws ClassNotFoundException {
  3. return loadClass(name, false);
  4. }
  5.  
  6. // sun.misc.Launcher
  7. public Class<?> loadClass(String var1, boolean var2) throws ClassNotFoundException {
  8. int var3 = var1.lastIndexOf(46);
  9. if(var3 != -1) {
  10. SecurityManager var4 = System.getSecurityManager();
  11. if(var4 != null) {
  12. var4.checkPackageAccess(var1.substring(0, var3));
  13. }
  14. }
  15.  
  16. if(this.ucp.knownToNotExist(var1)) {
  17. Class var5 = this.findLoadedClass(var1);
  18. if(var5 != null) {
  19. if(var2) {
  20. this.resolveClass(var5);
  21. }
  22.  
  23. return var5;
  24. } else {
  25. throw new ClassNotFoundException(var1);
  26. }
  27. } else {
  28. return super.loadClass(var1, var2);
  29. }
  30. }
  31. // java.lang.ClassLoader
  32. protected Class<?> loadClass(String name, boolean resolve)
  33. throws ClassNotFoundException
  34. {
  35. // 先获取锁
  36. synchronized (getClassLoadingLock(name)) {
  37. // First, check if the class has already been loaded
  38. // 如果已经加载了的话,就不用再加载了
  39. Class<?> c = findLoadedClass(name);
  40. if (c == null) {
  41. long t0 = System.nanoTime();
  42. try {
  43. // 双亲委托加载
  44. if (parent != null) {
  45. c = parent.loadClass(name, false);
  46. } else {
  47. c = findBootstrapClassOrNull(name);
  48. }
  49. } catch (ClassNotFoundException e) {
  50. // ClassNotFoundException thrown if class not found
  51. // from the non-null parent class loader
  52. }
  53.  
  54. // 父类没有加载到时,再自己加载
  55. if (c == null) {
  56. // If still not found, then invoke findClass in order
  57. // to find the class.
  58. long t1 = System.nanoTime();
  59. c = findClass(name);
  60.  
  61. // this is the defining class loader; record the stats
  62. sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
  63. sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  64. sun.misc.PerfCounter.getFindClasses().increment();
  65. }
  66. }
  67. if (resolve) {
  68. resolveClass(c);
  69. }
  70. return c;
  71. }
  72. }
  73.  
  74. protected Object getClassLoadingLock(String className) {
  75. Object lock = this;
  76. if (parallelLockMap != null) {
  77. // 使用 ConcurrentHashMap来保存锁
  78. Object newLock = new Object();
  79. lock = parallelLockMap.putIfAbsent(className, newLock);
  80. if (lock == null) {
  81. lock = newLock;
  82. }
  83. }
  84. return lock;
  85. }
  86.  
  87. protected final Class<?> findLoadedClass(String name) {
  88. if (!checkName(name))
  89. return null;
  90. return findLoadedClass0(name);
  91. }

  下面来看一下 newInstance() 的实现方式!

  1. // 首先肯定是 Class.newInstance
  2. @CallerSensitive
  3. public T newInstance()
  4. throws InstantiationException, IllegalAccessException
  5. {
  6. if (System.getSecurityManager() != null) {
  7. checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
  8. }
  9.  
  10. // NOTE: the following code may not be strictly correct under
  11. // the current Java memory model.
  12.  
  13. // Constructor lookup
  14. // newInstance() 其实相当于调用类的无参构造函数,所以,首先要找到其无参构造器
  15. if (cachedConstructor == null) {
  16. if (this == Class.class) {
  17. // 不允许调用 Class 的 newInstance() 方法
  18. throw new IllegalAccessException(
  19. "Can not call newInstance() on the Class for java.lang.Class"
  20. );
  21. }
  22. try {
  23. // 获取无参构造器
  24. Class<?>[] empty = {};
  25. final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
  26. // Disable accessibility checks on the constructor
  27. // since we have to do the security check here anyway
  28. // (the stack depth is wrong for the Constructor's
  29. // security check to work)
  30. java.security.AccessController.doPrivileged(
  31. new java.security.PrivilegedAction<Void>() {
  32. public Void run() {
  33. c.setAccessible(true);
  34. return null;
  35. }
  36. });
  37. cachedConstructor = c;
  38. } catch (NoSuchMethodException e) {
  39. throw (InstantiationException)
  40. new InstantiationException(getName()).initCause(e);
  41. }
  42. }
  43. Constructor<T> tmpConstructor = cachedConstructor;
  44. // Security check (same as in java.lang.reflect.Constructor)
  45. int modifiers = tmpConstructor.getModifiers();
  46. if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
  47. Class<?> caller = Reflection.getCallerClass();
  48. if (newInstanceCallerCache != caller) {
  49. Reflection.ensureMemberAccess(caller, this, null, modifiers);
  50. newInstanceCallerCache = caller;
  51. }
  52. }
  53. // Run constructor
  54. try {
  55. // 调用无参构造器
  56. return tmpConstructor.newInstance((Object[])null);
  57. } catch (InvocationTargetException e) {
  58. Unsafe.getUnsafe().throwException(e.getTargetException());
  59. // Not reached
  60. return null;
  61. }
  62. }

newInstance() 主要做了三件事:

  1. 权限检测,如果不通过直接抛出异常;

  2. 查找无参构造器,并将其缓存起来;

  3. 调用具体方法的无参构造方法,生成实例并返回;

下面是获取构造器的过程:

  1. private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
  2. int which) throws NoSuchMethodException
  3. {
  4. // 获取所有构造器
  5. Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
  6. for (Constructor<T> constructor : constructors) {
  7. if (arrayContentsEq(parameterTypes,
  8. constructor.getParameterTypes())) {
  9. return getReflectionFactory().copyConstructor(constructor);
  10. }
  11. }
  12. throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
  13. }

getConstructor0() 为获取匹配的构造方器;分三步:
  1. 先获取所有的constructors, 然后通过进行参数类型比较;
  2. 找到匹配后,通过 ReflectionFactory copy一份constructor返回;
  3. 否则抛出 NoSuchMethodException;

  1. // 获取当前类所有的构造方法,通过jvm或者缓存
  2. // Returns an array of "root" constructors. These Constructor
  3. // objects must NOT be propagated to the outside world, but must
  4. // instead be copied via ReflectionFactory.copyConstructor.
  5. private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
  6. checkInitted();
  7. Constructor<T>[] res;
  8. // 调用 reflectionData(), 获取保存的信息,使用软引用保存,从而使内存不够可以回收
  9. ReflectionData<T> rd = reflectionData();
  10. if (rd != null) {
  11. res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
  12. // 存在缓存,则直接返回
  13. if (res != null) return res;
  14. }
  15. // No cached value available; request value from VM
  16. if (isInterface()) {
  17. @SuppressWarnings("unchecked")
  18. Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
  19. res = temporaryRes;
  20. } else {
  21. // 使用native方法从jvm获取构造器
  22. res = getDeclaredConstructors0(publicOnly);
  23. }
  24. if (rd != null) {
  25. // 最后,将从jvm中读取的内容,存入缓存
  26. if (publicOnly) {
  27. rd.publicConstructors = res;
  28. } else {
  29. rd.declaredConstructors = res;
  30. }
  31. }
  32. return res;
  33. }
  34.  
  35. // Lazily create and cache ReflectionData
  36. private ReflectionData<T> reflectionData() {
  37. SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
  38. int classRedefinedCount = this.classRedefinedCount;
  39. ReflectionData<T> rd;
  40. if (useCaches &&
  41. reflectionData != null &&
  42. (rd = reflectionData.get()) != null &&
  43. rd.redefinedCount == classRedefinedCount) {
  44. return rd;
  45. }
  46. // else no SoftReference or cleared SoftReference or stale ReflectionData
  47. // -> create and replace new instance
  48. return newReflectionData(reflectionData, classRedefinedCount);
  49. }
  50.  
  51. // 新创建缓存,保存反射信息
  52. private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
  53. int classRedefinedCount) {
  54. if (!useCaches) return null;
  55.  
  56. // 使用cas保证更新的线程安全性,所以反射是保证线程安全的
  57. while (true) {
  58. ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
  59. // try to CAS it...
  60. if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
  61. return rd;
  62. }
  63. // 先使用CAS更新,如果更新成功,则立即返回,否则测查当前已被其他线程更新的情况,如果和自己想要更新的状态一致,则也算是成功了
  64. oldReflectionData = this.reflectionData;
  65. classRedefinedCount = this.classRedefinedCount;
  66. if (oldReflectionData != null &&
  67. (rd = oldReflectionData.get()) != null &&
  68. rd.redefinedCount == classRedefinedCount) {
  69. return rd;
  70. }
  71. }
  72. }

如上,privateGetDeclaredConstructors(), 获取所有的构造器主要步骤;
  1. 先尝试从缓存中获取;
  2. 如果缓存没有,则从jvm中重新获取,并存入缓存,缓存使用软引用进行保存,保证内存可用;

另外,使用 relactionData() 进行缓存保存;ReflectionData 的数据结构如下!

  1. // reflection data that might get invalidated when JVM TI RedefineClasses() is called
  2. private static class ReflectionData<T> {
  3. volatile Field[] declaredFields;
  4. volatile Field[] publicFields;
  5. volatile Method[] declaredMethods;
  6. volatile Method[] publicMethods;
  7. volatile Constructor<T>[] declaredConstructors;
  8. volatile Constructor<T>[] publicConstructors;
  9. // Intermediate results for getFields and getMethods
  10. volatile Field[] declaredPublicFields;
  11. volatile Method[] declaredPublicMethods;
  12. volatile Class<?>[] interfaces;
  13.  
  14. // Value of classRedefinedCount when we created this ReflectionData instance
  15. final int redefinedCount;
  16.  
  17. ReflectionData(int redefinedCount) {
  18. this.redefinedCount = redefinedCount;
  19. }
  20. }

  其中,还有一个点,就是如何比较构造是否是要查找构造器,其实就是比较类型完成相等就完了,有一个不相等则返回false。

  1. private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
  2. if (a1 == null) {
  3. return a2 == null || a2.length == 0;
  4. }
  5.  
  6. if (a2 == null) {
  7. return a1.length == 0;
  8. }
  9.  
  10. if (a1.length != a2.length) {
  11. return false;
  12. }
  13.  
  14. for (int i = 0; i < a1.length; i++) {
  15. if (a1[i] != a2[i]) {
  16. return false;
  17. }
  18. }
  19.  
  20. return true;
  21. }
  22. // sun.reflect.ReflectionFactory
  23. /** Makes a copy of the passed constructor. The returned
  24. constructor is a "child" of the passed one; see the comments
  25. in Constructor.java for details. */
  26. public <T> Constructor<T> copyConstructor(Constructor<T> arg) {
  27. return langReflectAccess().copyConstructor(arg);
  28. }
  29.  
  30. // java.lang.reflect.Constructor, copy 其实就是新new一个 Constructor 出来
  31. Constructor<T> copy() {
  32. // This routine enables sharing of ConstructorAccessor objects
  33. // among Constructor objects which refer to the same underlying
  34. // method in the VM. (All of this contortion is only necessary
  35. // because of the "accessibility" bit in AccessibleObject,
  36. // which implicitly requires that new java.lang.reflect
  37. // objects be fabricated for each reflective call on Class
  38. // objects.)
  39. if (this.root != null)
  40. throw new IllegalArgumentException("Can not copy a non-root Constructor");
  41.  
  42. Constructor<T> res = new Constructor<>(clazz,
  43. parameterTypes,
  44. exceptionTypes, modifiers, slot,
  45. signature,
  46. annotations,
  47. parameterAnnotations);
  48. // root 指向当前 constructor
  49. res.root = this;
  50. // Might as well eagerly propagate this if already present
  51. res.constructorAccessor = constructorAccessor;
  52. return res;
  53. }

  通过上面,获取到 Constructor 了!

接下来就只需调用其相应构造器的 newInstance(),即返回实例了!

  1. // return tmpConstructor.newInstance((Object[])null);
  2. // java.lang.reflect.Constructor
  3. @CallerSensitive
  4. public T newInstance(Object ... initargs)
  5. throws InstantiationException, IllegalAccessException,
  6. IllegalArgumentException, InvocationTargetException
  7. {
  8. if (!override) {
  9. if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
  10. Class<?> caller = Reflection.getCallerClass();
  11. checkAccess(caller, clazz, null, modifiers);
  12. }
  13. }
  14. if ((clazz.getModifiers() & Modifier.ENUM) != 0)
  15. throw new IllegalArgumentException("Cannot reflectively create enum objects");
  16. ConstructorAccessor ca = constructorAccessor; // read volatile
  17. if (ca == null) {
  18. ca = acquireConstructorAccessor();
  19. }
  20. @SuppressWarnings("unchecked")
  21. T inst = (T) ca.newInstance(initargs);
  22. return inst;
  23. }
  24. // sun.reflect.DelegatingConstructorAccessorImpl
  25. public Object newInstance(Object[] args)
  26. throws InstantiationException,
  27. IllegalArgumentException,
  28. InvocationTargetException
  29. {
  30. return delegate.newInstance(args);
  31. }
  32. // sun.reflect.NativeConstructorAccessorImpl
  33. public Object newInstance(Object[] args)
  34. throws InstantiationException,
  35. IllegalArgumentException,
  36. InvocationTargetException
  37. {
  38. // We can't inflate a constructor belonging to a vm-anonymous class
  39. // because that kind of class can't be referred to by name, hence can't
  40. // be found from the generated bytecode.
  41. if (++numInvocations > ReflectionFactory.inflationThreshold()
  42. && !ReflectUtil.isVMAnonymousClass(c.getDeclaringClass())) {
  43. ConstructorAccessorImpl acc = (ConstructorAccessorImpl)
  44. new MethodAccessorGenerator().
  45. generateConstructor(c.getDeclaringClass(),
  46. c.getParameterTypes(),
  47. c.getExceptionTypes(),
  48. c.getModifiers());
  49. parent.setDelegate(acc);
  50. }
  51.  
  52. // 调用native方法,进行调用 constructor
  53. return newInstance0(c, args);
  54. }

  返回构造器的实例后,可以根据外部进行进行类型转换,从而使用接口或方法进行调用实例功能了。

2. 反射获取方法 c.class.getDeclaredMethod();Method.invoke() 反射调用方法!

  第一步,先获取 Method;

  1. // java.lang.Class
  2. @CallerSensitive
  3. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  4. throws NoSuchMethodException, SecurityException {
  5. checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
  6. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  7. if (method == null) {
  8. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  9. }
  10. return method;
  11. }

忽略第一个检查权限,剩下就只有两个动作了!
  1. 获取所有方法列表;
  2. 根据方法名称和方法列表,选出符合要求的方法;
  3. 如果没有找到相应方法,抛出异常,否则返回对应方法;

  所以,先看一下怎样获取类声明的所有方法?

  1. // Returns an array of "root" methods. These Method objects must NOT
  2. // be propagated to the outside world, but must instead be copied
  3. // via ReflectionFactory.copyMethod.
  4. private Method[] privateGetDeclaredMethods(boolean publicOnly) {
  5. checkInitted();
  6. Method[] res;
  7. ReflectionData<T> rd = reflectionData();
  8. if (rd != null) {
  9. res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
  10. if (res != null) return res;
  11. }
  12. // No cached value available; request value from VM
  13. res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
  14. if (rd != null) {
  15. if (publicOnly) {
  16. rd.declaredPublicMethods = res;
  17. } else {
  18. rd.declaredMethods = res;
  19. }
  20. }
  21. return res;
  22. }

  很相似,和获取所有构造器的方法很相似,都是先从缓存中获取方法,如果没有,则从jvm中获取!

  不同的是,方法列表需要进行过滤 Reflection.filterMethods;当然后面看来,这个方法我们一般不会派上用场!

  1. // sun.misc.Reflection
  2. public static Method[] filterMethods(Class<?> containingClass, Method[] methods) {
  3. if (methodFilterMap == null) {
  4. // Bootstrapping
  5. return methods;
  6. }
  7. return (Method[])filter(methods, methodFilterMap.get(containingClass));
  8. }
  9. // 可以过滤指定的方法,一般为空,如果要指定过滤,可以调用 registerMethodsToFilter(), 或者...
  10. private static Member[] filter(Member[] members, String[] filteredNames) {
  11. if ((filteredNames == null) || (members.length == 0)) {
  12. return members;
  13. }
  14. int numNewMembers = 0;
  15. for (Member member : members) {
  16. boolean shouldSkip = false;
  17. for (String filteredName : filteredNames) {
  18. if (member.getName() == filteredName) {
  19. shouldSkip = true;
  20. break;
  21. }
  22. }
  23. if (!shouldSkip) {
  24. ++numNewMembers;
  25. }
  26. }
  27. Member[] newMembers =
  28. (Member[])Array.newInstance(members[0].getClass(), numNewMembers);
  29. int destIdx = 0;
  30. for (Member member : members) {
  31. boolean shouldSkip = false;
  32. for (String filteredName : filteredNames) {
  33. if (member.getName() == filteredName) {
  34. shouldSkip = true;
  35. break;
  36. }
  37. }
  38. if (!shouldSkip) {
  39. newMembers[destIdx++] = member;
  40. }
  41. }
  42. return newMembers;
  43. }

  第二步,根据方法名和参数类型过滤指定方法返回:

  1. private static Method searchMethods(Method[] methods,
  2. String name,
  3. Class<?>[] parameterTypes)
  4. {
  5. Method res = null;
  6. // 使用常量池,避免重复创建String
  7. String internedName = name.intern();
  8. for (int i = 0; i < methods.length; i++) {
  9. Method m = methods[i];
  10. if (m.getName() == internedName
  11. && arrayContentsEq(parameterTypes, m.getParameterTypes())
  12. && (res == null
  13. || res.getReturnType().isAssignableFrom(m.getReturnType())))
  14. res = m;
  15. }
  16.  
  17. return (res == null ? res : getReflectionFactory().copyMethod(res));
  18. }

大概意思看得明白,就是匹配到方法名,然后参数类型匹配,才可以!
  但是,可以看到,匹配到一个方法,并没有退出for循环,而是继续进行匹配!
  这里,是匹配最精确的子类进行返回(最优匹配)
  最后,还是通过 ReflectionFactory, copy 方法后返回!

第三步,调用 method.invoke() 方法!

  1. @CallerSensitive
  2. public Object invoke(Object obj, Object... args)
  3. throws IllegalAccessException, IllegalArgumentException,
  4. InvocationTargetException
  5. {
  6. if (!override) {
  7. if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
  8. Class<?> caller = Reflection.getCallerClass();
  9. checkAccess(caller, clazz, obj, modifiers);
  10. }
  11. }
  12. MethodAccessor ma = methodAccessor; // read volatile
  13. if (ma == null) {
  14. ma = acquireMethodAccessor();
  15. }
  16. return ma.invoke(obj, args);
  17. }

  invoke时,是通过 MethodAccessor 进行调用的,而 MethodAccessor 是个接口,在第一次时调用 acquireMethodAccessor() 进行新创建!

  1. // probably make the implementation more scalable.
  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,否则调用 ReflectionFactory 创建新的 MethodAccessor
  9. methodAccessor = tmp;
  10. } else {
  11. // Otherwise fabricate one and propagate it up to the root
  12. tmp = reflectionFactory.newMethodAccessor(this);
  13. setMethodAccessor(tmp);
  14. }
  15.  
  16. return tmp;
  17. }
  18. // sun.reflect.ReflectionFactory
  19. public MethodAccessor newMethodAccessor(Method method) {
  20. checkInitted();
  21.  
  22. if (noInflation && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
  23. return new MethodAccessorGenerator().
  24. generateMethod(method.getDeclaringClass(),
  25. method.getName(),
  26. method.getParameterTypes(),
  27. method.getReturnType(),
  28. method.getExceptionTypes(),
  29. method.getModifiers());
  30. } else {
  31. NativeMethodAccessorImpl acc =
  32. new NativeMethodAccessorImpl(method);
  33. DelegatingMethodAccessorImpl res =
  34. new DelegatingMethodAccessorImpl(acc);
  35. acc.setParent(res);
  36. return res;
  37. }
  38. }

两个Accessor详情:

  1. // NativeMethodAccessorImpl / DelegatingMethodAccessorImpl
  2. class NativeMethodAccessorImpl extends MethodAccessorImpl {
  3. private final Method method;
  4. private DelegatingMethodAccessorImpl parent;
  5. private int numInvocations;
  6.  
  7. NativeMethodAccessorImpl(Method method) {
  8. this.method = method;
  9. }
  10.  
  11. public Object invoke(Object obj, Object[] args)
  12. throws IllegalArgumentException, InvocationTargetException
  13. {
  14. // We can't inflate methods belonging to vm-anonymous classes because
  15. // that kind of class can't be referred to by name, hence can't be
  16. // found from the generated bytecode.
  17. if (++numInvocations > ReflectionFactory.inflationThreshold()
  18. && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
  19. MethodAccessorImpl acc = (MethodAccessorImpl)
  20. new MethodAccessorGenerator().
  21. generateMethod(method.getDeclaringClass(),
  22. method.getName(),
  23. method.getParameterTypes(),
  24. method.getReturnType(),
  25. method.getExceptionTypes(),
  26. method.getModifiers());
  27. parent.setDelegate(acc);
  28. }
  29.  
  30. return invoke0(method, obj, args);
  31. }
  32.  
  33. void setParent(DelegatingMethodAccessorImpl parent) {
  34. this.parent = parent;
  35. }
  36.  
  37. private static native Object invoke0(Method m, Object obj, Object[] args);
  38. }
  39. class DelegatingMethodAccessorImpl extends MethodAccessorImpl {
  40. private MethodAccessorImpl delegate;
  41.  
  42. DelegatingMethodAccessorImpl(MethodAccessorImpl delegate) {
  43. setDelegate(delegate);
  44. }
  45.  
  46. public Object invoke(Object obj, Object[] args)
  47. throws IllegalArgumentException, InvocationTargetException
  48. {
  49. return delegate.invoke(obj, args);
  50. }
  51.  
  52. void setDelegate(MethodAccessorImpl delegate) {
  53. this.delegate = delegate;
  54. }
  55. }

  进行 ma.invoke(obj, args); 调用时,调用 DelegatingMethodAccessorImpl.invoke();

  最后被委托到 NativeMethodAccessorImpl.invoke(), 即:

  1. public Object invoke(Object obj, Object[] args)
  2. throws IllegalArgumentException, InvocationTargetException
  3. {
  4. // We can't inflate methods belonging to vm-anonymous classes because
  5. // that kind of class can't be referred to by name, hence can't be
  6. // found from the generated bytecode.
  7. if (++numInvocations > ReflectionFactory.inflationThreshold()
  8. && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
  9. MethodAccessorImpl acc = (MethodAccessorImpl)
  10. new MethodAccessorGenerator().
  11. generateMethod(method.getDeclaringClass(),
  12. method.getName(),
  13. method.getParameterTypes(),
  14. method.getReturnType(),
  15. method.getExceptionTypes(),
  16. method.getModifiers());
  17. parent.setDelegate(acc);
  18. }
  19.  
  20. // invoke0 是个 native 方法,由jvm进行调用业务方法!从而完成反射调用功能!
  21. return invoke0(method, obj, args);
  22. }

  其中, generateMethod() 是生成具体类的方法:

  1. /** This routine is not thread-safe */
  2. public MethodAccessor generateMethod(Class<?> declaringClass,
  3. String name,
  4. Class<?>[] parameterTypes,
  5. Class<?> returnType,
  6. Class<?>[] checkedExceptions,
  7. int modifiers)
  8. {
  9. return (MethodAccessor) generate(declaringClass,
  10. name,
  11. parameterTypes,
  12. returnType,
  13. checkedExceptions,
  14. modifiers,
  15. false,
  16. false,
  17. null);
  18. }

generate() 戳详情!

  1. /** This routine is not thread-safe */
  2. private MagicAccessorImpl generate(final Class<?> declaringClass,
  3. String name,
  4. Class<?>[] parameterTypes,
  5. Class<?> returnType,
  6. Class<?>[] checkedExceptions,
  7. int modifiers,
  8. boolean isConstructor,
  9. boolean forSerialization,
  10. Class<?> serializationTargetClass)
  11. {
  12. ByteVector vec = ByteVectorFactory.create();
  13. asm = new ClassFileAssembler(vec);
  14. this.declaringClass = declaringClass;
  15. this.parameterTypes = parameterTypes;
  16. this.returnType = returnType;
  17. this.modifiers = modifiers;
  18. this.isConstructor = isConstructor;
  19. this.forSerialization = forSerialization;
  20.  
  21. asm.emitMagicAndVersion();
  22.  
  23. // Constant pool entries:
  24. // ( * = Boxing information: optional)
  25. // (+ = Shared entries provided by AccessorGenerator)
  26. // (^ = Only present if generating SerializationConstructorAccessor)
  27. // [UTF-8] [This class's name]
  28. // [CONSTANT_Class_info] for above
  29. // [UTF-8] "sun/reflect/{MethodAccessorImpl,ConstructorAccessorImpl,SerializationConstructorAccessorImpl}"
  30. // [CONSTANT_Class_info] for above
  31. // [UTF-8] [Target class's name]
  32. // [CONSTANT_Class_info] for above
  33. // ^ [UTF-8] [Serialization: Class's name in which to invoke constructor]
  34. // ^ [CONSTANT_Class_info] for above
  35. // [UTF-8] target method or constructor name
  36. // [UTF-8] target method or constructor signature
  37. // [CONSTANT_NameAndType_info] for above
  38. // [CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info] for target method
  39. // [UTF-8] "invoke" or "newInstance"
  40. // [UTF-8] invoke or newInstance descriptor
  41. // [UTF-8] descriptor for type of non-primitive parameter 1
  42. // [CONSTANT_Class_info] for type of non-primitive parameter 1
  43. // ...
  44. // [UTF-8] descriptor for type of non-primitive parameter n
  45. // [CONSTANT_Class_info] for type of non-primitive parameter n
  46. // + [UTF-8] "java/lang/Exception"
  47. // + [CONSTANT_Class_info] for above
  48. // + [UTF-8] "java/lang/ClassCastException"
  49. // + [CONSTANT_Class_info] for above
  50. // + [UTF-8] "java/lang/NullPointerException"
  51. // + [CONSTANT_Class_info] for above
  52. // + [UTF-8] "java/lang/IllegalArgumentException"
  53. // + [CONSTANT_Class_info] for above
  54. // + [UTF-8] "java/lang/InvocationTargetException"
  55. // + [CONSTANT_Class_info] for above
  56. // + [UTF-8] "<init>"
  57. // + [UTF-8] "()V"
  58. // + [CONSTANT_NameAndType_info] for above
  59. // + [CONSTANT_Methodref_info] for NullPointerException's constructor
  60. // + [CONSTANT_Methodref_info] for IllegalArgumentException's constructor
  61. // + [UTF-8] "(Ljava/lang/String;)V"
  62. // + [CONSTANT_NameAndType_info] for "<init>(Ljava/lang/String;)V"
  63. // + [CONSTANT_Methodref_info] for IllegalArgumentException's constructor taking a String
  64. // + [UTF-8] "(Ljava/lang/Throwable;)V"
  65. // + [CONSTANT_NameAndType_info] for "<init>(Ljava/lang/Throwable;)V"
  66. // + [CONSTANT_Methodref_info] for InvocationTargetException's constructor
  67. // + [CONSTANT_Methodref_info] for "super()"
  68. // + [UTF-8] "java/lang/Object"
  69. // + [CONSTANT_Class_info] for above
  70. // + [UTF-8] "toString"
  71. // + [UTF-8] "()Ljava/lang/String;"
  72. // + [CONSTANT_NameAndType_info] for "toString()Ljava/lang/String;"
  73. // + [CONSTANT_Methodref_info] for Object's toString method
  74. // + [UTF-8] "Code"
  75. // + [UTF-8] "Exceptions"
  76. // * [UTF-8] "java/lang/Boolean"
  77. // * [CONSTANT_Class_info] for above
  78. // * [UTF-8] "(Z)V"
  79. // * [CONSTANT_NameAndType_info] for above
  80. // * [CONSTANT_Methodref_info] for above
  81. // * [UTF-8] "booleanValue"
  82. // * [UTF-8] "()Z"
  83. // * [CONSTANT_NameAndType_info] for above
  84. // * [CONSTANT_Methodref_info] for above
  85. // * [UTF-8] "java/lang/Byte"
  86. // * [CONSTANT_Class_info] for above
  87. // * [UTF-8] "(B)V"
  88. // * [CONSTANT_NameAndType_info] for above
  89. // * [CONSTANT_Methodref_info] for above
  90. // * [UTF-8] "byteValue"
  91. // * [UTF-8] "()B"
  92. // * [CONSTANT_NameAndType_info] for above
  93. // * [CONSTANT_Methodref_info] for above
  94. // * [UTF-8] "java/lang/Character"
  95. // * [CONSTANT_Class_info] for above
  96. // * [UTF-8] "(C)V"
  97. // * [CONSTANT_NameAndType_info] for above
  98. // * [CONSTANT_Methodref_info] for above
  99. // * [UTF-8] "charValue"
  100. // * [UTF-8] "()C"
  101. // * [CONSTANT_NameAndType_info] for above
  102. // * [CONSTANT_Methodref_info] for above
  103. // * [UTF-8] "java/lang/Double"
  104. // * [CONSTANT_Class_info] for above
  105. // * [UTF-8] "(D)V"
  106. // * [CONSTANT_NameAndType_info] for above
  107. // * [CONSTANT_Methodref_info] for above
  108. // * [UTF-8] "doubleValue"
  109. // * [UTF-8] "()D"
  110. // * [CONSTANT_NameAndType_info] for above
  111. // * [CONSTANT_Methodref_info] for above
  112. // * [UTF-8] "java/lang/Float"
  113. // * [CONSTANT_Class_info] for above
  114. // * [UTF-8] "(F)V"
  115. // * [CONSTANT_NameAndType_info] for above
  116. // * [CONSTANT_Methodref_info] for above
  117. // * [UTF-8] "floatValue"
  118. // * [UTF-8] "()F"
  119. // * [CONSTANT_NameAndType_info] for above
  120. // * [CONSTANT_Methodref_info] for above
  121. // * [UTF-8] "java/lang/Integer"
  122. // * [CONSTANT_Class_info] for above
  123. // * [UTF-8] "(I)V"
  124. // * [CONSTANT_NameAndType_info] for above
  125. // * [CONSTANT_Methodref_info] for above
  126. // * [UTF-8] "intValue"
  127. // * [UTF-8] "()I"
  128. // * [CONSTANT_NameAndType_info] for above
  129. // * [CONSTANT_Methodref_info] for above
  130. // * [UTF-8] "java/lang/Long"
  131. // * [CONSTANT_Class_info] for above
  132. // * [UTF-8] "(J)V"
  133. // * [CONSTANT_NameAndType_info] for above
  134. // * [CONSTANT_Methodref_info] for above
  135. // * [UTF-8] "longValue"
  136. // * [UTF-8] "()J"
  137. // * [CONSTANT_NameAndType_info] for above
  138. // * [CONSTANT_Methodref_info] for above
  139. // * [UTF-8] "java/lang/Short"
  140. // * [CONSTANT_Class_info] for above
  141. // * [UTF-8] "(S)V"
  142. // * [CONSTANT_NameAndType_info] for above
  143. // * [CONSTANT_Methodref_info] for above
  144. // * [UTF-8] "shortValue"
  145. // * [UTF-8] "()S"
  146. // * [CONSTANT_NameAndType_info] for above
  147. // * [CONSTANT_Methodref_info] for above
  148.  
  149. short numCPEntries = NUM_BASE_CPOOL_ENTRIES + NUM_COMMON_CPOOL_ENTRIES;
  150. boolean usesPrimitives = usesPrimitiveTypes();
  151. if (usesPrimitives) {
  152. numCPEntries += NUM_BOXING_CPOOL_ENTRIES;
  153. }
  154. if (forSerialization) {
  155. numCPEntries += NUM_SERIALIZATION_CPOOL_ENTRIES;
  156. }
  157.  
  158. // Add in variable-length number of entries to be able to describe
  159. // non-primitive parameter types and checked exceptions.
  160. numCPEntries += (short) (2 * numNonPrimitiveParameterTypes());
  161.  
  162. asm.emitShort(add(numCPEntries, S1));
  163.  
  164. final String generatedName = generateName(isConstructor, forSerialization);
  165. asm.emitConstantPoolUTF8(generatedName);
  166. asm.emitConstantPoolClass(asm.cpi());
  167. thisClass = asm.cpi();
  168. if (isConstructor) {
  169. if (forSerialization) {
  170. asm.emitConstantPoolUTF8
  171. ("sun/reflect/SerializationConstructorAccessorImpl");
  172. } else {
  173. asm.emitConstantPoolUTF8("sun/reflect/ConstructorAccessorImpl");
  174. }
  175. } else {
  176. asm.emitConstantPoolUTF8("sun/reflect/MethodAccessorImpl");
  177. }
  178. asm.emitConstantPoolClass(asm.cpi());
  179. superClass = asm.cpi();
  180. asm.emitConstantPoolUTF8(getClassName(declaringClass, false));
  181. asm.emitConstantPoolClass(asm.cpi());
  182. targetClass = asm.cpi();
  183. short serializationTargetClassIdx = (short) 0;
  184. if (forSerialization) {
  185. asm.emitConstantPoolUTF8(getClassName(serializationTargetClass, false));
  186. asm.emitConstantPoolClass(asm.cpi());
  187. serializationTargetClassIdx = asm.cpi();
  188. }
  189. asm.emitConstantPoolUTF8(name);
  190. asm.emitConstantPoolUTF8(buildInternalSignature());
  191. asm.emitConstantPoolNameAndType(sub(asm.cpi(), S1), asm.cpi());
  192. if (isInterface()) {
  193. asm.emitConstantPoolInterfaceMethodref(targetClass, asm.cpi());
  194. } else {
  195. if (forSerialization) {
  196. asm.emitConstantPoolMethodref(serializationTargetClassIdx, asm.cpi());
  197. } else {
  198. asm.emitConstantPoolMethodref(targetClass, asm.cpi());
  199. }
  200. }
  201. targetMethodRef = asm.cpi();
  202. if (isConstructor) {
  203. asm.emitConstantPoolUTF8("newInstance");
  204. } else {
  205. asm.emitConstantPoolUTF8("invoke");
  206. }
  207. invokeIdx = asm.cpi();
  208. if (isConstructor) {
  209. asm.emitConstantPoolUTF8("([Ljava/lang/Object;)Ljava/lang/Object;");
  210. } else {
  211. asm.emitConstantPoolUTF8
  212. ("(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
  213. }
  214. invokeDescriptorIdx = asm.cpi();
  215.  
  216. // Output class information for non-primitive parameter types
  217. nonPrimitiveParametersBaseIdx = add(asm.cpi(), S2);
  218. for (int i = 0; i < parameterTypes.length; i++) {
  219. Class<?> c = parameterTypes[i];
  220. if (!isPrimitive(c)) {
  221. asm.emitConstantPoolUTF8(getClassName(c, false));
  222. asm.emitConstantPoolClass(asm.cpi());
  223. }
  224. }
  225.  
  226. // Entries common to FieldAccessor, MethodAccessor and ConstructorAccessor
  227. emitCommonConstantPoolEntries();
  228.  
  229. // Boxing entries
  230. if (usesPrimitives) {
  231. emitBoxingContantPoolEntries();
  232. }
  233.  
  234. if (asm.cpi() != numCPEntries) {
  235. throw new InternalError("Adjust this code (cpi = " + asm.cpi() +
  236. ", numCPEntries = " + numCPEntries + ")");
  237. }
  238.  
  239. // Access flags
  240. asm.emitShort(ACC_PUBLIC);
  241.  
  242. // This class
  243. asm.emitShort(thisClass);
  244.  
  245. // Superclass
  246. asm.emitShort(superClass);
  247.  
  248. // Interfaces count and interfaces
  249. asm.emitShort(S0);
  250.  
  251. // Fields count and fields
  252. asm.emitShort(S0);
  253.  
  254. // Methods count and methods
  255. asm.emitShort(NUM_METHODS);
  256.  
  257. emitConstructor();
  258. emitInvoke();
  259.  
  260. // Additional attributes (none)
  261. asm.emitShort(S0);
  262.  
  263. // Load class
  264. vec.trim();
  265. final byte[] bytes = vec.getData();
  266. // Note: the class loader is the only thing that really matters
  267. // here -- it's important to get the generated code into the
  268. // same namespace as the target class. Since the generated code
  269. // is privileged anyway, the protection domain probably doesn't
  270. // matter.
  271. return AccessController.doPrivileged(
  272. new PrivilegedAction<MagicAccessorImpl>() {
  273. public MagicAccessorImpl run() {
  274. try {
  275. return (MagicAccessorImpl)
  276. ClassDefiner.defineClass
  277. (generatedName,
  278. bytes,
  279. 0,
  280. bytes.length,
  281. declaringClass.getClassLoader()).newInstance();
  282. } catch (InstantiationException | IllegalAccessException e) {
  283. throw new InternalError(e);
  284. }
  285. }
  286. });
  287. }

咱们主要看这一句:ClassDefiner.defineClass(xx, declaringClass.getClassLoader()).newInstance();

在ClassDefiner.defineClass方法实现中,每被调用一次都会生成一个DelegatingClassLoader类加载器对象 ,这里每次都生成新的类加载器,是为了性能考虑,在某些情况下可以卸载这些生成的类,因为类的卸载是只有在类加载器可以被回收的情况下才会被回收的,如果用了原来的类加载器,那可能导致这些新创建的类一直无法被卸载!

而反射生成的类,有时候可能用了就可以卸载了,所以使用其独立的类加载器,从而使得更容易控制反射类的生命周期!

最后,用几句话总结反射的实现原理:

1. 反射类及反射方法的获取,都是通过从列表中搜寻查找匹配的方法,所以查找性能会随类的大小方法多少而变化;

2. 每个类都会有一个与之对应的Class实例,从而每个类都可以获取method反射方法,并作用到其他实例身上;

3. 反射也是考虑了线程安全的,放心使用;

4. 反射使用软引用relectionData缓存class信息,避免每次重新从jvm获取带来的开销;

5. 反射调用多次生成新代理Accessor, 而通过字节码生存的则考虑了卸载功能,所以会使用独立的类加载器;

6. 当找到需要的方法,都会copy一份出来,而不是使用原来的实例,从而保证数据隔离;

7. 调度反射方法,最终是由jvm执行invoke0()执行;

深入理解java反射原理的更多相关文章

  1. 《深入理解Java虚拟机》虚拟机性能监控与故障处理工具

    上节学习回顾 从课本章节划分,<垃圾收集器>和<内存分配策略>这两篇随笔同属一章节,主要是从理论+实验的手段来讲解JVM的内存处理机制.好让我们对JVM运行机制有一个良好的概念 ...

  2. 深入理解Java 8 Lambda(语言篇——lambda,方法引用,目标类型和默认方法)

    作者:Lucida 微博:@peng_gong 豆瓣:@figure9 原文链接:http://zh.lucida.me/blog/java-8-lambdas-insideout-language- ...

  3. java笔记--理解java类加载器以及ClassLoader类

    类加载器概述: java类的加载是由虚拟机来完成的,虚拟机把描述类的Class文件加载到内存,并对数据进行校验,解析和初始化,最终形成能被java虚拟机直接使用的java类型,这就是虚拟机的类加载机制 ...

  4. 《深入理解Java内存模型》读书总结

    概要 文章是<深入理解Java内容模型>读书笔记,该书总共包括了3部分的知识. 第1部分,基本概念 包括"并发.同步.主内存.本地内存.重排序.内存屏障.happens befo ...

  5. 深入理解Java的接口和抽象类(转)

    深入理解Java的接口和抽象类 对于面向对象编程来说,抽象是它的一大特征之一.在Java中,可以通过两种形式来体现OOP的抽象:接口和抽象类.这两者有太多相似的地方,又有太多不同的地方.很多人在初学的 ...

  6. 《深入理解 java虚拟机》学习笔记

    java内存区域详解 以下内容参考自<深入理解 java虚拟机 JVM高级特性与最佳实践>,其中图片大多取自网络与本书,以供学习和参考.

  7. 【转】深入理解 Java 垃圾回收机制

    深入理解 Java 垃圾回收机制   一.垃圾回收机制的意义 Java语言中一个显著的特点就是引入了垃圾回收机制,使c++程序员最头疼的内存管理的问题迎刃而解,它使得Java程序员在编写程序的时候不再 ...

  8. 深入理解java内存模型系列文章

    转载关于java内存模型的系列文章,写的非常好. 深入理解java内存模型(一)--基础 深入理解java内存模型(二)--重排序 深入理解java内存模型(三)--顺序一致性 深入理解java内存模 ...

  9. 深入理解Java的接口和抽象类

    深入理解Java的接口和抽象类 对于面向对象编程来说,抽象是它的一大特征之一.在Java中,可以通过两种形式来体现OOP的抽象:接口和抽象类.这两者有太多相似的地方,又有太多不同的地方.很多人在初学的 ...

随机推荐

  1. springmvc webservlet 异步请求总结

    1:每次请求会启动一个新线程 上边在debug状态下, 每次请求一次,生成一个新的 thread  在此已经是245了 出现一个现象在debug模式下, 每次请求生成的线程,自动在红框那个位置停了下来 ...

  2. 常用的三种json软件的使用

    从几个角度比较三种软件 1. json操作 2 反解 3 性能 易用性还没有列出. 可以根据个人喜好进行取舍. package json; import com.alibaba.fastjson.JS ...

  3. Cannot retrieve metalink for repository: epel/x86_64. Please verify its path and try again

    虚拟机恢复快照后,使用yum安装软件,提示下面的信息,开始以为是yum源的问题或者DNS的问题,但是无果,最后再看一下服务器的时间,坑了,还原快照,时间变成以前的了. [root@localhost ...

  4. 464. Can I Win

    https://leetcode.com/problems/can-i-win/description/ In the "100 game," two players take t ...

  5. Innodb 状态的部分解释

    Innodb_buffer_pool_pages_data Innodb buffer pool缓存池中包含数据的页的数目,包括脏页.单位是page. Innodb_buffer_pool_pages ...

  6. 别人的Linux私房菜(17)进程管理与SELinux初探

    程序在磁盘中,通过用户的执行触发.触发事件时,加载到内存,系统将它定义成进程,给予进程PID,根据触发的用户和属性,给予PID合适的权限. PID和登陆者的UID/GID有关.父进程衍生出来的进程为子 ...

  7. django的视图函数

    一.视图函数view 视图函数是接收一个请求(request对象),并返回响应的函数 1. HttpResponse响应请求 这个方法是返回字符串一类的,可以识别标签 2. render响应请求 re ...

  8. flume接收http请求,并将数据写到kafka

    flume接收http请求,并将数据写到kafka,spark消费kafka的数据.是数据采集的经典框架. 直接上flume的配置: source : http channel : file sink ...

  9. 解决css冲突的问题

    在各个框架中,每个例子都会自带一些样式. 拼接的时候都是全局的,或者同样修改了某个地方,就会产生冲突. 方法一: 首先导入全局,然后再导入其他的进行覆盖 方法二: 给样式添加作用域,只要当前作用域中起 ...

  10. mysql 截取替换某个字符串

    SELECT m.content,o.order_price,o.id,m.id FROM scp_home_msg m INNER JOIN scp_order o ON m.link_id=o.i ...