反射的使用

获取class对象的三种方式

  1. //类名全路径
  2. Class<?> clazz1 = Class.forName("test.User");
  3. Class clazz2 = User.class;
  4. Class clazz3 = new User().getClass();

获取构造方法

  1. // 获取"参数是parameterTypes"的public的构造函数
  2. public Constructor getConstructor(Class[] parameterTypes)
  3. // 获取全部的public的构造函数
  4. public Constructor[] getConstructors()
  5. // 获取"参数是parameterTypes"的,并且是类自身声明的构造函数,包含public、protected和private方法
  6. public Constructor getDeclaredConstructor(Class[] parameterTypes)
  7. // 获取类自身声明的全部的构造函数,包含public、protected和private方法
  8. public Constructor[] getDeclaredConstructors()
  9. // 如果这个类是"其它类的构造函数中的内部类",
  10. 调用getEnclosingConstructor()就是这个类所在的构造函数;若不存在,返回null
  11. public Constructor getEnclosingConstructor()
  1. Class<?> clazz = Class.forName("test.User");
  2. //获得默认构造函数
  3. Constructor<?> constructor = clazz.getDeclaredConstructor(null);
  4. Object object1 = constructor.newInstance();
  5. //获得含参构造函数
  6. Constructor<?> constructor2 = clazz.getDeclaredConstructor(new Class[]
  7. {int.class, String.class});
  8. Object object2 = constructor2.newInstance(1, "123456");

获取成员方法

  1. // 获取“名称是name,参数是parameterTypes”的public的函数
  2. (包括从基类继承的、从接口实现的所有public函数)
  3. public Method getMethod(String name, Class[] parameterTypes)
  4. // 获取全部的public的函数(包括从基类继承的、从接口实现的所有public函数)
  5. public Method[] getMethods()
  6. // 获取“名称是name,参数是parameterTypes”,
  7. 并且是类自身声明的函数,包含publicprotectedprivate方法。
  8. public Method getDeclaredMethod(String name, Class[] parameterTypes)
  9. // 获取全部的类自身声明的函数,包含public、protected和private方法。
  10. public Method[] getDeclaredMethods()
  11. // 如果这个类是“其它类中某个方法的内部类”,
  12. 调用getEnclosingMethod()就是这个类所在的方法;若不存在,返回null
  13. public Method getEnclosingMethod()
  1. Class<?> clazz = Class.forName("test.User");
  2. //获取全部的类自身声明的函数,包含public、protected和private方法。
  3. Method[] declaredMethods = clazz.getDeclaredMethods();
  4. //获取方法名为printInfo,方法参数类型任意的方法
  5. Method printInfo = clazz.getDeclaredMethod("printInfo", new Class[]{});
  6. User user = (User) clazz.newInstance();
  7. //invoke传入的参数是这个方法所属的对象,以及方法的参数
  8. //可以调用类中的任意方法,包括私有方法
  9. printInfo.invoke(user, null);

获取成员变量

  1. // 获取“名称是name”的public的成员变量(包括从基类继承的、从接口实现的所有public成员变量)
  2. public Field getField(String name)
  3. // 获取全部的public成员变量(包括从基类继承的、从接口实现的所有public成员变量)
  4. public Field[] getFields()
  5. // 获取“名称是name”,并且是类自身声明的成员变量,包含public、protected和private成员变量。
  6. public Field getDeclaredField(String name)
  7. // 获取全部的类自身声明的成员变量,包含public、protected和private成员变量。
  8. public Field[] getDeclaredFields()
  1. Class<?> clazz = Class.forName("test.User");
  2. Field[] fields = clazz.getDeclaredFields();
  3. // 创建并通过反射,修改一个 private 变量 id
  4. User user = (User) clazz.newInstance();
  5. Field field = clazz.getDeclaredField("id");
  6. //private属性要设置为true
  7. field.setAccessible(true);
  8. field.set(user, 123);

获取注解和父类

  1. // 获取类的"annotationClass"类型的注解
  2. public Annotation<A> getAnnotation(Class annotationClass)
  3. // 获取类的全部注解,不能获取继承的注解
  4. public Annotation[] getAnnotations()
  5. // 获取类自身声明的全部注解
  6. public Annotation[] getDeclaredAnnotations()
  7. // 获取实现的全部接口
  8. public Type[] getGenericInterfaces()
  9. // 获取父类
  10. public Type getGenericSuperclass()

反射源码分析

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. }
  18. //acquireMethodAccessor()
  19. private MethodAccessor acquireMethodAccessor() {
  20. // First check to see if one has been created yet, and take it
  21. // if so
  22. MethodAccessor tmp = null;
  23. if (root != null) tmp = root.getMethodAccessor();
  24. if (tmp != null) {
  25. methodAccessor = tmp;
  26. } else {
  27. // Otherwise fabricate one and propagate it up to the root
  28. tmp = reflectionFactory.newMethodAccessor(this);
  29. setMethodAccessor(tmp);
  30. }
  31. return tmp;
  32. }
  33. public MethodAccessor newMethodAccessor(Method var1) {
  34. checkInitted();
  35. //MethodAccessor的实现由两种,if走MethodAccessorGenerator,
  36. elseNativeMethodAccessorImpl
  37. 反射次数超过15次则走if分支
  38. if (noInflation && !ReflectUtil.isVMAnonymousClass(var1.getDeclaringClass())) {
  39. return (new MethodAccessorGenerator()).
  40. generateMethod(var1.getDeclaringClass(), var1.getName(),
  41. var1.getParameterTypes(), var1.getReturnType(),
  42. var1.getExceptionTypes(), var1.getModifiers());
  43. } else {
  44. //代理模式的实现
  45. NativeMethodAccessorImpl var2 = new NativeMethodAccessorImpl(var1);
  46. DelegatingMethodAccessorImpl var3 = new DelegatingMethodAccessorImpl(var2);
  47. //var2保存var3的引用
  48. var2.setParent(var3);
  49. return var3;
  50. }
  51. }

静态代理模式的标准实现

  1. class NativeMethodAccessorImpl extends MethodAccessorImpl {
  2. private final Method method;
  3. private DelegatingMethodAccessorImpl parent;
  4. private int numInvocations;
  5. NativeMethodAccessorImpl(Method var1) {
  6. this.method = var1;
  7. }
  8. public Object invoke(Object var1, Object[] var2) throws IllegalArgumentException,
  9. InvocationTargetException {
  10. if (++this.numInvocations > ReflectionFactory.inflationThreshold() &&
  11. !ReflectUtil.isVMAnonymousClass(this.method.getDeclaringClass())) {
  12. MethodAccessorImpl var3 = (MethodAccessorImpl)
  13. (new MethodAccessorGenerator())
  14. . generateMethod(this.method.getDeclaringClass(), this.method.getName(),
  15. this.method.getParameterTypes(),
  16. this.method.getReturnType(),
  17. this.method.getExceptionTypes(),
  18. this.method.getModifiers());
  19. this.parent.setDelegate(var3);
  20. }
  21. return invoke0(this.method, var1, var2);
  22. }
  23. void setParent(DelegatingMethodAccessorImpl var1) {
  24. this.parent = var1;
  25. }
  26. private static native Object invoke0(Method var0, Object var1, Object[] var2);
  27. }
  1. class DelegatingMethodAccessorImpl extends MethodAccessorImpl {
  2. private MethodAccessorImpl delegate;
  3. DelegatingMethodAccessorImpl(MethodAccessorImpl var1) {
  4. this.setDelegate(var1);
  5. }
  6. public Object invoke(Object var1, Object[] var2) throws IllegalArgumentException, InvocationTargetException {
  7. return this.delegate.invoke(var1, var2);
  8. }
  9. void setDelegate(MethodAccessorImpl var1) {
  10. this.delegate = var1;
  11. }
  12. }

NativeMethodAccessorImplDelegatingMethodAccessorImpl继承自同一个类MethodAccessorImpl
DelegatingMethodAccessorImpl根据传入的MethodAccessorImpl对象来调用其invoke方法。

NativeMethodAccessorImpl.invoke()

  1. public Object invoke(Object var1, Object[] var2) throws IllegalArgumentException,
  2. InvocationTargetException {
  3. //判断numInvocations的阈值并且不是内部类
  4. if (++this.numInvocations > ReflectionFactory.inflationThreshold() &&
  5. !ReflectUtil.isVMAnonymousClass(this.method.getDeclaringClass())) {
  6. MethodAccessorImpl var3 = (MethodAccessorImpl)
  7. (new MethodAccessorGenerator())
  8. . generateMethod(this.method.getDeclaringClass(), this.method.getName(),
  9. this.method.getParameterTypes(),
  10. this.method.getReturnType(),
  11. this.method.getExceptionTypes(),
  12. this.method.getModifiers());
  13. this.parent.setDelegate(var3);
  14. }
  15. return invoke0(this.method, var1, var2);
  16. }