代码解释:java反射调用的原理

//首先是反射的调用的方法
	InvocationHandler test = new TestHander(new UserImpl());
		User user = (User) Proxy.newProxyInstance(UserImpl.class.getClassLoader(),
				UserImpl.class.getInterfaces(), test );//代码@处
		String Id = "00001";
		user.addUser(Id);
//test为自定义的代理类,我们弄清的是,Proxy.newProxyInstance()时发生了什么?以及user.addUser()方法
//是如何调用的

//首先是Proxy.newProxyInstance()的源码
//类java.lang.reflect.Proxy的部分的源码

public static Object newProxyInstance(ClassLoader loader,
					  Class<?>[] interfaces,
					  InvocationHandler h)
	throws IllegalArgumentException
    {
	if (h == null) {
	    throw new NullPointerException();
	}

	/*
	 * Look up or generate the designated proxy class.
	 * 查找或者生成指定的代理类
	 */
	Class cl = getProxyClass(loader, interfaces);//①关键的地方

	/*
	 * Invoke its constructor with the designated invocation handler.
	 *  调用指定代理处理程序的构造函数,本程序中就是h的构造方法
	 */
	try {

		/*
		 * parameter types of a proxy class constructor 代理类的构造函数
		 * private final static Class[] constructorParams ={ InvocationHandler.class };
		 * 运行的时候就是,$Proxy0(InvocationHandler h)
		 */
	    Constructor cons = cl.getConstructor(constructorParams);
	    // 生成代理类的实例 参量h传给它的构造方法  
	    return (Object) cons.newInstance(new Object[] { h });//代码*处
	} catch (NoSuchMethodException e) {
	    throw new InternalError(e.toString());
	} catch (IllegalAccessException e) {
	    throw new InternalError(e.toString());
	} catch (InstantiationException e) {
	    throw new InternalError(e.toString());
	} catch (InvocationTargetException e) {
	    throw new InternalError(e.toString());
	}
    }

    //关键的代码①的地方,首先确定传入的值得确定
    //@para loader = (UserImpl.class.getClassLocator = sun.misc.Launcher$AppClassLoader@18d107f)
    //@para interfaces = (UserImpl.class.getInterface = interface proxy.User )(这里的proxy指的是程序中的包名)


     public static Class<?> getProxyClass(ClassLoader loader, 
                                         Class<?>... interfaces)
	throws IllegalArgumentException
    {
    	//接口的数量的限制,只能表示佩服。。。
	if (interfaces.length > 65535) {
	    throw new IllegalArgumentException("interface limit exceeded");
	}
	//声明代理对象所代表的class 对象,这个是返回的对象
	Class proxyClass = null;

	/* collect interface names to use as key for proxy class cache */
	/* 接口的名字的集合作为代理对象的缓存的key值*/
	String[] interfaceNames = new String[interfaces.length];//key值

	Set interfaceSet = new HashSet();	// for detecting duplicates 去重

	for (int i = 0; i < interfaces.length; i++) {
	    /*
	     * Verify that the class loader resolves the name of this
	     * interface to the same Class object.
	     */
	    // 接口的名称,例如 interface proxy.User
	    String interfaceName = interfaces[i].getName();
	    // 加载目标类实现的接口,可能不止一个,就是接口的class对象 到内存中
	    Class interfaceClass = null;
	    try {
		interfaceClass = Class.forName(interfaceName, false, loader);
	    } catch (ClassNotFoundException e) {
	    }
	    //这个判断和异常比较的有意思??
	    if (interfaceClass != interfaces[i]) {
		throw new IllegalArgumentException(
		    interfaces[i] + " is not visible from class loader");
	    }

	    /*
	     * Verify that the Class object actually represents an
	     * interface.
	     */
	    if (!interfaceClass.isInterface()) {
		throw new IllegalArgumentException(
		    interfaceClass.getName() + " is not an interface");
	    }

	    /*
	     * Verify that this interface is not a duplicate.
	     */
	    if (interfaceSet.contains(interfaceClass)) {
		throw new IllegalArgumentException(
		    "repeated interface: " + interfaceClass.getName());
	    }
	    //把目标类实现的接口代表的Class对象放到Set中 
	    interfaceSet.add(interfaceClass);

	    interfaceNames[i] = interfaceName;
	}

	/*
	 * Using string representations of the proxy interfaces as
	 * keys in the proxy class cache (instead of their Class
	 * objects) is sufficient because we require the proxy
	 * interfaces to be resolvable by name through the supplied
	 * class loader, and it has the advantage that using a string
	 * representation of a class makes for an implicit weak
	 * reference to the class.
	 */
	//这里是所有的接口名称,作为key值,上面是说明为什么用这个作为key值得
	Object key = Arrays.asList(interfaceNames);

	/*
	 * Find or create the proxy class cache for the class loader.
	 */
	Map cache;
	synchronized (loaderToCache) {
		//从缓存中找到类加载对象
	    cache = (Map) loaderToCache.get(loader);
	    if (cache == null) {
	    	//没有的话,新建一个hashMap,把当前的类加载器loader和新建的hashMap放进去
		cache = new HashMap();
		loaderToCache.put(loader, cache);
	    }
	    /*
	     * This mapping will remain valid for the duration of this
	     * method, without further synchronization, because the mapping
	     * will only be removed if the class loader becomes unreachable.
	     */
	}

	/*
	 * Look up the list of interfaces in the proxy class cache using
	 * the key.  This lookup will result in one of three possible
	 * kinds of values:
	 *     null, if there is currently no proxy class for the list of
	 *         interfaces in the class loader,
	 *     the pendingGenerationMarker object, if a proxy class for the
	 *         list of interfaces is currently being generated,
	 *     or a weak reference to a Class object, if a proxy class for
	 *         the list of interfaces has already been generated.
	 */
	synchronized (cache) {
	    /*
	     * Note that we need not worry about reaping the cache for
	     * entries with cleared weak references because if a proxy class
	     * has been garbage collected, its class loader will have been
	     * garbage collected as well, so the entire cache will be reaped
	     * from the loaderToCache map.
	     */
	    do {
		Object value = cache.get(key);
		if (value instanceof Reference) {
		    proxyClass = (Class) ((Reference) value).get();
		}
		if (proxyClass != null) {
		    // proxy class already generated: return it
		    return proxyClass;
		} else if (value == pendingGenerationMarker) {
		    // proxy class being generated: wait for it
		    try {
			cache.wait();
		    } catch (InterruptedException e) {
			/*
			 * The class generation that we are waiting for should
			 * take a small, bounded time, so we can safely ignore
			 * thread interrupts here.
			 */
		    }
		    continue;
		} else {
		    /*
		     * No proxy class for this list of interfaces has been
		     * generated or is being generated, so we will go and
		     * generate it now.  Mark it as pending generation.
		     */
		    cache.put(key, pendingGenerationMarker);
		    break;
		}
	    } while (true);
	}

	try {
	    String proxyPkg = null;	// package to define proxy class in

	    /*
	     * Record the package of a non-public proxy interface so that the
	     * proxy class will be defined in the same package.  Verify that
	     * all non-public proxy interfaces are in the same package.
	     */
	    for (int i = 0; i < interfaces.length; i++) {
		int flags = interfaces[i].getModifiers();
		if (!Modifier.isPublic(flags)) {
		    String name = interfaces[i].getName();
		    int n = name.lastIndexOf('.');
		    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
		    if (proxyPkg == null) {
			proxyPkg = pkg;
		    } else if (!pkg.equals(proxyPkg)) {
			throw new IllegalArgumentException(
			    "non-public interfaces from different packages");
		    }
		}
	    }

	    if (proxyPkg == null) {	// if no non-public proxy interfaces,
		proxyPkg = "";		// use the unnamed package
	    }

	    {
		/*
		 * Choose a name for the proxy class to generate.
		 */
		long num;
		synchronized (nextUniqueNumberLock) {
		    num = nextUniqueNumber++;
		}
		String proxyName = proxyPkg + proxyClassNamePrefix + num;
		/*
		 * Verify that the class loader hasn't already
		 * defined a class with the chosen name.
		 */

		/*
		 * Generate the specified proxy class.
		 */
		//② 比较重要的地方,生产成了代理对象,根据proxyName一般是$proxy0和interfaces
		byte[] proxyClassFile =	ProxyGenerator.generateProxyClass(
		    proxyName, interfaces);
		try {
			// ③根据代理类的字节码生成代理类的实例
		    proxyClass = defineClass0(loader, proxyName,
			proxyClassFile, 0, proxyClassFile.length);
		} catch (ClassFormatError e) {
		    /*
		     * A ClassFormatError here means that (barring bugs in the
		     * proxy class generation code) there was some other
		     * invalid aspect of the arguments supplied to the proxy
		     * class creation (such as virtual machine limitations
		     * exceeded).
		     */
		    throw new IllegalArgumentException(e.toString());
		}
	    }
	    // add to set of all generated proxy classes, for isProxyClass
	    proxyClasses.put(proxyClass, null);

	} finally {
	    /*
	     * We must clean up the "pending generation" state of the proxy
	     * class cache entry somehow.  If a proxy class was successfully
	     * generated, store it in the cache (with a weak reference);
	     * otherwise, remove the reserved entry.  In all cases, notify
	     * all waiters on reserved entries in this cache.
	     */
	    synchronized (cache) {
		if (proxyClass != null) {
		    cache.put(key, new WeakReference(proxyClass));
		} else {
		    cache.remove(key);
		}
		cache.notifyAll();
	    }
	}
	return proxyClass;
    }

//下面就是根据proxyName和接口的对象 生成字节码的过程
 public static byte[] generateProxyClass(final String name,
                                            Class[] interfaces)
    {
        ProxyGenerator gen = new ProxyGenerator(name, interfaces);
		// 这里动态生成代理类的字节码,由于比较复杂就不进去看了
        final byte[] classFile = gen.generateClassFile();

		// 如果saveGeneratedFiles的值为true,则会把所生成的代理类的字节码保存到硬盘上
        if (saveGeneratedFiles) {
            java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    try {
                        FileOutputStream file =
                            new FileOutputStream(dotToSlash(name) + ".class");
                        file.write(classFile);
                        file.close();
                        return null;
                    } catch (IOException e) {
                        throw new InternalError(
                            "I/O exception saving generated file: " + e);
                    }
                }
            });
        }

		// 返回代理类的字节码
        return classFile;
    }

    //现在是,我们知道了newInstance,生成了代理类的字节码,这个过程已经了解了,那么
    //下一个问题就是:user.add()方法的调用,也就是说是哪个类调用的InvocationHandler的invoke方法的
    //那么我们,就要看一下JDK生成的字节码是一个什么样的东西,对应的是一个什么样的逻辑,可以使用一下的
    //方法获取JDK为我们生成的字节码写到硬盘中,我们在利用反编译工具,查看其中的逻辑
    //方法来源:http://rejoy.iteye.com/blog/1627405
    public class ProxyGeneratorUtils {
	/**
	 * 把代理类的字节码写到硬盘上
	 */
	public static void writeProxyClassToHardDisk(String path) {

		// 获取代理类的字节码
		byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy11",
				UserImpl.class.getInterfaces());

		FileOutputStream out = null;

		try {
			out = new FileOutputStream(path);
			out.write(classFile);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void testGenerateProxyClass() {  
        ProxyGeneratorUtils.writeProxyClassToHardDisk("F:/$Proxy11.class");  
    }  
}
   //程序生成的字节码反编译的代码是:

   public final class $Proxy11 extends Proxy
  implements User
{
  private static Method m3;
  private static Method m1;
  private static Method m0;
  private static Method m2;
  //构造函数,其中参数,对应代码*处
  public $Proxy11(InvocationHandler paramInvocationHandler)
    throws 
  {
    super(paramInvocationHandler);
  }

  //这个就是我们所要找的user.addUser(Id)的调用的地方
  public final void addUser(String paramString)
    throws 
  {
    try
    {
    	//实际就是h处invoke的方法,就是代码@处 自定义的代理处理类的invoke的地方
    	//这样就与实际的代码执行,相吻合
      this.h.invoke(this, m3, new Object[] { paramString });
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final boolean equals(Object paramObject)
    throws 
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final int hashCode()
    throws 
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final String toString()
    throws 
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  static
  {
    try
    {
    //在静态代码块中获取了4个方法:Object中的equals方法、User中的addUser方法、Object中的hashCode方法、Object中toString方法
      m3 = Class.forName("proxy.User").getMethod("addUser", new Class[] { Class.forName("java.lang.String") });
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    }
  }
} 

/*
 * 总结来看,总算知道了反射时,JDK究竟是如何调用的。不足的地方就是代理类的字节码是如何生成的,依据什么,
 * 仍不是很清楚,不过根据反编译的代码,大致的能够找到一点蛛丝马迹
 */



具体的执行的源码:附件不会上传啊,郁闷

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值