JDK动态代理实现原理

来源:互联网 发布:观为监测大数据 编辑:程序博客网 时间:2024/05/16 02:04

地址:http://rejoy.iteye.com/blog/1627405

jdk动态代理之所以只能代理接口是因为代理类本身已经extends了Proxy,而Java是不允许多重继承的,但是允许实现多个接口,因此才有cglib的需要吧

jdk的代理是利用反射生成字节码,并生成对象,
cglib是直接修改目标类的字节码生成对象,所以性能+

之前虽然会用JDK的动态代理,但是有些问题却一直没有搞明白。比如说:InvocationHandler的invoke方法是由谁来调用的,代理对象是怎么生成的,直到前几个星期才把这些问题全部搞明白了。 

    废话不多说了,先来看一下JDK的动态是怎么用的。 

Java代码  收藏代码
  1. package dynamic.proxy;   
  2.   
  3. import java.lang.reflect.InvocationHandler;  
  4. import java.lang.reflect.Method;  
  5. import java.lang.reflect.Proxy;  
  6.   
  7. /** 
  8.  * 实现自己的InvocationHandler 
  9.  * @author zyb 
  10.  * @since 2012-8-9 
  11.  * 
  12.  */  
  13. public class MyInvocationHandler implements InvocationHandler {  
  14.       
  15.     // 目标对象   
  16.     private Object target;  
  17.       
  18.     /** 
  19.      * 构造方法 
  20.      * @param target 目标对象  
  21.      */  
  22.     public MyInvocationHandler(Object target) {  
  23.         super();  
  24.         this.target = target;  
  25.     }  
  26.   
  27.   
  28.     /** 
  29.      * 执行目标对象的方法 
  30.      */  
  31.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  32.           
  33.         // 在目标对象的方法执行之前简单的打印一下  
  34.         System.out.println("------------------before------------------");  
  35.           
  36.         // 执行目标对象的方法  
  37.         Object result = method.invoke(target, args);  
  38.           
  39.         // 在目标对象的方法执行之后简单的打印一下  
  40.         System.out.println("-------------------after------------------");  
  41.           
  42.         return result;  
  43.     }  
  44.   
  45.     /** 
  46.      * 获取目标对象的代理对象 
  47.      * @return 代理对象 
  48.      */  
  49.     public Object getProxy() {  
  50.         return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),   
  51.                 target.getClass().getInterfaces(), this);  
  52.     }  
  53. }  
  54.   
  55. package dynamic.proxy;  
  56.   
  57. /** 
  58.  * 目标对象实现的接口,用JDK来生成代理对象一定要实现一个接口 
  59.  * @author zyb 
  60.  * @since 2012-8-9 
  61.  * 
  62.  */  
  63. public interface UserService {  
  64.   
  65.     /** 
  66.      * 目标方法  
  67.      */  
  68.     public abstract void add();  
  69.   
  70. }  
  71.   
  72. package dynamic.proxy;   
  73.   
  74. /** 
  75.  * 目标对象 
  76.  * @author zyb 
  77.  * @since 2012-8-9 
  78.  * 
  79.  */  
  80. public class UserServiceImpl implements UserService {  
  81.   
  82.     /* (non-Javadoc) 
  83.      * @see dynamic.proxy.UserService#add() 
  84.      */  
  85.     public void add() {  
  86.         System.out.println("--------------------add---------------");  
  87.     }  
  88. }  
  89.   
  90. package dynamic.proxy;   
  91.   
  92. import org.junit.Test;  
  93.   
  94. /** 
  95.  * 动态代理测试类 
  96.  * @author zyb 
  97.  * @since 2012-8-9 
  98.  * 
  99.  */  
  100. public class ProxyTest {  
  101.   
  102.     @Test  
  103.     public void testProxy() throws Throwable {  
  104.         // 实例化目标对象  
  105.         UserService userService = new UserServiceImpl();  
  106.           
  107.         // 实例化InvocationHandler  
  108.         MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);  
  109.           
  110.         // 根据目标对象生成代理对象  
  111.         UserService proxy = (UserService) invocationHandler.getProxy();  
  112.           
  113.         // 调用代理对象的方法  
  114.         proxy.add();  
  115.           
  116.     }  
  117. }  


执行结果如下: 
------------------before------------------ 
--------------------add--------------- 
-------------------after------------------
 

   用起来是很简单吧,其实这里基本上就是AOP的一个简单实现了,在目标对象的方法执行之前和执行之后进行了增强。Spring的AOP实现其实也是用了Proxy和InvocationHandler这两个东西的。 

    用起来是比较简单,但是如果能知道它背后做了些什么手脚,那就更好不过了。首先来看一下JDK是怎样生成代理对象的。既然生成代理对象是用的Proxy类的静态方newProxyInstance,那么我们就去它的源码里看一下它到底都做了些什么? 
Java代码  收藏代码
  1. /** 
  2.  * loader:类加载器 
  3.  * interfaces:目标对象实现的接口 
  4.  * h:InvocationHandler的实现类 
  5.  */  
  6. public static Object newProxyInstance(ClassLoader loader,  
  7.                       Class<?>[] interfaces,  
  8.                       InvocationHandler h)  
  9.     throws IllegalArgumentException  
  10.     {  
  11.     if (h == null) {  
  12.         throw new NullPointerException();  
  13.     }  
  14.   
  15.     /* 
  16.      * Look up or generate the designated proxy class. 
  17.      */  
  18.     Class cl = getProxyClass(loader, interfaces);  
  19.   
  20.     /* 
  21.      * Invoke its constructor with the designated invocation handler. 
  22.      */  
  23.     try {  
  24.             // 调用代理对象的构造方法(也就是$Proxy0(InvocationHandler h))  
  25.         Constructor cons = cl.getConstructor(constructorParams);  
  26.             // 生成代理类的实例并把MyInvocationHandler的实例传给它的构造方法  
  27.         return (Object) cons.newInstance(new Object[] { h });  
  28.     } catch (NoSuchMethodException e) {  
  29.         throw new InternalError(e.toString());  
  30.     } catch (IllegalAccessException e) {  
  31.         throw new InternalError(e.toString());  
  32.     } catch (InstantiationException e) {  
  33.         throw new InternalError(e.toString());  
  34.     } catch (InvocationTargetException e) {  
  35.         throw new InternalError(e.toString());  
  36.     }  
  37.     }  


   我们再进去getProxyClass方法看一下 
Java代码  收藏代码
  1. public static Class<?> getProxyClass(ClassLoader loader,   
  2.                                          Class<?>... interfaces)  
  3.     throws IllegalArgumentException  
  4.     {  
  5.     // 如果目标类实现的接口数大于65535个则抛出异常(我XX,谁会写这么NB的代码啊?)  
  6.     if (interfaces.length > 65535) {  
  7.         throw new IllegalArgumentException("interface limit exceeded");  
  8.     }  
  9.   
  10.     // 声明代理对象所代表的Class对象(有点拗口)  
  11.     Class proxyClass = null;  
  12.   
  13.     String[] interfaceNames = new String[interfaces.length];  
  14.   
  15.     Set interfaceSet = new HashSet();   // for detecting duplicates  
  16.   
  17.     // 遍历目标类所实现的接口  
  18.     for (int i = 0; i < interfaces.length; i++) {  
  19.           
  20.         // 拿到目标类实现的接口的名称  
  21.         String interfaceName = interfaces[i].getName();  
  22.         Class interfaceClass = null;  
  23.         try {  
  24.         // 加载目标类实现的接口到内存中  
  25.         interfaceClass = Class.forName(interfaceName, false, loader);  
  26.         } catch (ClassNotFoundException e) {  
  27.         }  
  28.         if (interfaceClass != interfaces[i]) {  
  29.         throw new IllegalArgumentException(  
  30.             interfaces[i] + " is not visible from class loader");  
  31.         }  
  32.   
  33.         // 中间省略了一些无关紧要的代码 .......  
  34.           
  35.         // 把目标类实现的接口代表的Class对象放到Set中  
  36.         interfaceSet.add(interfaceClass);  
  37.   
  38.         interfaceNames[i] = interfaceName;  
  39.     }  
  40.   
  41.     // 把目标类实现的接口名称作为缓存(Map)中的key  
  42.     Object key = Arrays.asList(interfaceNames);  
  43.   
  44.     Map cache;  
  45.       
  46.     synchronized (loaderToCache) {  
  47.         // 从缓存中获取cache  
  48.         cache = (Map) loaderToCache.get(loader);  
  49.         if (cache == null) {  
  50.         // 如果获取不到,则新建地个HashMap实例  
  51.         cache = new HashMap();  
  52.         // 把HashMap实例和当前加载器放到缓存中  
  53.         loaderToCache.put(loader, cache);  
  54.         }  
  55.   
  56.     }  
  57.   
  58.     synchronized (cache) {  
  59.   
  60.         do {  
  61.         // 根据接口的名称从缓存中获取对象  
  62.         Object value = cache.get(key);  
  63.         if (value instanceof Reference) {  
  64.             proxyClass = (Class) ((Reference) value).get();  
  65.         }  
  66.         if (proxyClass != null) {  
  67.             // 如果代理对象的Class实例已经存在,则直接返回  
  68.             return proxyClass;  
  69.         } else if (value == pendingGenerationMarker) {  
  70.             try {  
  71.             cache.wait();  
  72.             } catch (InterruptedException e) {  
  73.             }  
  74.             continue;  
  75.         } else {  
  76.             cache.put(key, pendingGenerationMarker);  
  77.             break;  
  78.         }  
  79.         } while (true);  
  80.     }  
  81.   
  82.     try {  
  83.         // 中间省略了一些代码 .......  
  84.           
  85.         // 这里就是动态生成代理对象的最关键的地方  
  86.         byte[] proxyClassFile = ProxyGenerator.generateProxyClass(  
  87.             proxyName, interfaces);  
  88.         try {  
  89.             // 根据代理类的字节码生成代理类的实例  
  90.             proxyClass = defineClass0(loader, proxyName,  
  91.             proxyClassFile, 0, proxyClassFile.length);  
  92.         } catch (ClassFormatError e) {  
  93.             throw new IllegalArgumentException(e.toString());  
  94.         }  
  95.         }  
  96.         // add to set of all generated proxy classes, for isProxyClass  
  97.         proxyClasses.put(proxyClass, null);  
  98.   
  99.     }   
  100.     // 中间省略了一些代码 .......  
  101.       
  102.     return proxyClass;  
  103.     }  


进去ProxyGenerator类的静态方法generateProxyClass,这里是真正生成代理类class字节码的地方。 
Java代码  收藏代码
  1. public static byte[] generateProxyClass(final String name,  
  2.                                            Class[] interfaces)  
  3.    {  
  4.        ProxyGenerator gen = new ProxyGenerator(name, interfaces);  
  5.     // 这里动态生成代理类的字节码,由于比较复杂就不进去看了  
  6.        final byte[] classFile = gen.generateClassFile();  
  7.   
  8.     // 如果saveGeneratedFiles的值为true,则会把所生成的代理类的字节码保存到硬盘上  
  9.        if (saveGeneratedFiles) {  
  10.            java.security.AccessController.doPrivileged(  
  11.            new java.security.PrivilegedAction<Void>() {  
  12.                public Void run() {  
  13.                    try {  
  14.                        FileOutputStream file =  
  15.                            new FileOutputStream(dotToSlash(name) + ".class");  
  16.                        file.write(classFile);  
  17.                        file.close();  
  18.                        return null;  
  19.                    } catch (IOException e) {  
  20.                        throw new InternalError(  
  21.                            "I/O exception saving generated file: " + e);  
  22.                    }  
  23.                }  
  24.            });  
  25.        }  
  26.   
  27.     // 返回代理类的字节码  
  28.        return classFile;  
  29.    }  


现在,JDK是怎样动态生成代理类的字节的原理已经一目了然了。 

好了,再来解决另外一个问题,那就是由谁来调用InvocationHandler的invoke方法的。要解决这个问题就要看一下JDK到底为我们生成了一个什么东西。用以下代码可以获取到JDK为我们生成的字节码并写到硬盘中。 
Java代码  收藏代码
  1. package dynamic.proxy;   
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. import sun.misc.ProxyGenerator;  
  7.   
  8. /** 
  9.  * 代理类的生成工具 
  10.  * @author zyb 
  11.  * @since 2012-8-9 
  12.  */  
  13. public class ProxyGeneratorUtils {  
  14.   
  15.     /** 
  16.      * 把代理类的字节码写到硬盘上 
  17.      * @param path 保存路径 
  18.      */  
  19.     public static void writeProxyClassToHardDisk(String path) {  
  20.         // 第一种方法,这种方式在刚才分析ProxyGenerator时已经知道了  
  21.         // System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", true);  
  22.           
  23.         // 第二种方法  
  24.           
  25.         // 获取代理类的字节码  
  26.         byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy11", UserServiceImpl.class.getInterfaces());  
  27.           
  28.         FileOutputStream out = null;  
  29.           
  30.         try {  
  31.             out = new FileOutputStream(path);  
  32.             out.write(classFile);  
  33.             out.flush();  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         } finally {  
  37.             try {  
  38.                 out.close();  
  39.             } catch (IOException e) {  
  40.                 e.printStackTrace();  
  41.             }  
  42.         }  
  43.     }  
  44. }  
  45.   
  46. package dynamic.proxy;   
  47.   
  48. import org.junit.Test;  
  49.   
  50. /** 
  51.  * 动态代理测试类 
  52.  * @author zyb 
  53.  * @since 2012-8-9 
  54.  * 
  55.  */  
  56. public class ProxyTest {  
  57.   
  58.     @Test  
  59.     public void testProxy() throws Throwable {  
  60.         // 实例化目标对象  
  61.         UserService userService = new UserServiceImpl();  
  62.           
  63.         // 实例化InvocationHandler  
  64.         MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);  
  65.           
  66.         // 根据目标对象生成代理对象  
  67.         UserService proxy = (UserService) invocationHandler.getProxy();  
  68.           
  69.         // 调用代理对象的方法  
  70.         proxy.add();  
  71.           
  72.     }  
  73.       
  74.     @Test  
  75.     public void testGenerateProxyClass() {  
  76.         ProxyGeneratorUtils.writeProxyClassToHardDisk("F:/$Proxy11.class");  
  77.     }  
  78. }  


通过以上代码,就可以在F盘上生成一个$Proxy.class文件了,现在用反编译工具来看一下这个class文件里面的内容。 
Java代码  收藏代码
  1. // Decompiled by DJ v3.11.11.95 Copyright 2009 Atanas Neshkov  Date: 2012/8/9 20:11:32  
  2. // Home Page: http://members.fortunecity.com/neshkov/dj.html  http://www.neshkov.com/dj.html - Check often for new version!  
  3. // Decompiler options: packimports(3)   
  4.   
  5. import dynamic.proxy.UserService;  
  6. import java.lang.reflect.*;  
  7.   
  8. public final class $Proxy11 extends Proxy  
  9.     implements UserService  
  10. {  
  11.   
  12.     // 构造方法,参数就是刚才传过来的MyInvocationHandler类的实例  
  13.     public $Proxy11(InvocationHandler invocationhandler)  
  14.     {  
  15.         super(invocationhandler);  
  16.     }  
  17.   
  18.     public final boolean equals(Object obj)  
  19.     {  
  20.         try  
  21.         {  
  22.             return ((Boolean)super.h.invoke(this, m1, new Object[] {  
  23.                 obj  
  24.             })).booleanValue();  
  25.         }  
  26.         catch(Error _ex) { }  
  27.         catch(Throwable throwable)  
  28.         {  
  29.             throw new UndeclaredThrowableException(throwable);  
  30.         }  
  31.     }  
  32.   
  33.     /** 
  34.      * 这个方法是关键部分 
  35.      */  
  36.     public final void add()  
  37.     {  
  38.         try  
  39.         {  
  40.             // 实际上就是调用MyInvocationHandler的public Object invoke(Object proxy, Method method, Object[] args)方法,第二个问题就解决了  
  41.             super.h.invoke(this, m3, null);  
  42.             return;  
  43.         }  
  44.         catch(Error _ex) { }  
  45.         catch(Throwable throwable)  
  46.         {  
  47.             throw new UndeclaredThrowableException(throwable);  
  48.         }  
  49.     }  
  50.   
  51.     public final int hashCode()  
  52.     {  
  53.         try  
  54.         {  
  55.             return ((Integer)super.h.invoke(this, m0, null)).intValue();  
  56.         }  
  57.         catch(Error _ex) { }  
  58.         catch(Throwable throwable)  
  59.         {  
  60.             throw new UndeclaredThrowableException(throwable);  
  61.         }  
  62.     }  
  63.   
  64.     public final String toString()  
  65.     {  
  66.         try  
  67.         {  
  68.             return (String)super.h.invoke(this, m2, null);  
  69.         }  
  70.         catch(Error _ex) { }  
  71.         catch(Throwable throwable)  
  72.         {  
  73.             throw new UndeclaredThrowableException(throwable);  
  74.         }  
  75.     }  
  76.   
  77.     private static Method m1;  
  78.     private static Method m3;  
  79.     private static Method m0;  
  80.     private static Method m2;  
  81.   
  82.     // 在静态代码块中获取了4个方法:Object中的equals方法、UserService中的add方法、Object中的hashCode方法、Object中toString方法  
  83.     static   
  84.     {  
  85.         try  
  86.         {  
  87.             m1 = Class.forName("java.lang.Object").getMethod("equals"new Class[] {  
  88.                 Class.forName("java.lang.Object")  
  89.             });  
  90.             m3 = Class.forName("dynamic.proxy.UserService").getMethod("add"new Class[0]);  
  91.             m0 = Class.forName("java.lang.Object").getMethod("hashCode"new Class[0]);  
  92.             m2 = Class.forName("java.lang.Object").getMethod("toString"new Class[0]);  
  93.         }  
  94.         catch(NoSuchMethodException nosuchmethodexception)  
  95.         {  
  96.             throw new NoSuchMethodError(nosuchmethodexception.getMessage());  
  97.         }  
  98.         catch(ClassNotFoundException classnotfoundexception)  
  99.         {  
  100.             throw new NoClassDefFoundError(classnotfoundexception.getMessage());  
  101.         }  
  102.     }  
  103. }  


好了,到目前为止,前面 的两个问题都已经知道回事了,现在再用JDK动态代理的时候就不只会用而已了,真正的达到了“知其然,知其所以然”的目的。。。   

就写到这了,累死了。。  

附上核心类Proxy源码:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. 
  3.  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 
  4.  */  
  5.   
  6. package java.lang.reflect;  
  7.   
  8. import java.lang.ref.Reference;  
  9. import java.lang.ref.WeakReference;  
  10. import java.security.AccessController;  
  11. import java.security.Permission;  
  12. import java.security.PrivilegedAction;  
  13. import java.util.Arrays;  
  14. import java.util.Collections;  
  15. import java.util.HashMap;  
  16. import java.util.HashSet;  
  17. import java.util.Map;  
  18. import java.util.Set;  
  19. import java.util.WeakHashMap;  
  20. import sun.misc.ProxyGenerator;  
  21. import sun.reflect.Reflection;  
  22. import sun.reflect.misc.ReflectUtil;  
  23. import sun.security.util.SecurityConstants;  
  24.   
  25. /** 
  26.  * <code>Proxy</code> provides static methods for creating dynamic proxy 
  27.  * classes and instances, and it is also the superclass of all 
  28.  * dynamic proxy classes created by those methods. 
  29.  * 
  30.  * <p>To create a proxy for some interface <code>Foo</code>: 
  31.  * <pre> 
  32.  *     InvocationHandler handler = new MyInvocationHandler(...); 
  33.  *     Class proxyClass = Proxy.getProxyClass( 
  34.  *         Foo.class.getClassLoader(), new Class[] { Foo.class }); 
  35.  *     Foo f = (Foo) proxyClass. 
  36.  *         getConstructor(new Class[] { InvocationHandler.class }). 
  37.  *         newInstance(new Object[] { handler }); 
  38.  * </pre> 
  39.  * or more simply: 
  40.  * <pre> 
  41.  *     Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), 
  42.  *                                          new Class[] { Foo.class }, 
  43.  *                                          handler); 
  44.  * </pre> 
  45.  * 
  46.  * <p>A <i>dynamic proxy class</i> (simply referred to as a <i>proxy 
  47.  * class</i> below) is a class that implements a list of interfaces 
  48.  * specified at runtime when the class is created, with behavior as 
  49.  * described below. 
  50.  * 
  51.  * A <i>proxy interface</i> is such an interface that is implemented 
  52.  * by a proxy class. 
  53.  * 
  54.  * A <i>proxy instance</i> is an instance of a proxy class. 
  55.  * 
  56.  * Each proxy instance has an associated <i>invocation handler</i> 
  57.  * object, which implements the interface {@link InvocationHandler}. 
  58.  * A method invocation on a proxy instance through one of its proxy 
  59.  * interfaces will be dispatched to the {@link InvocationHandler#invoke 
  60.  * invoke} method of the instance's invocation handler, passing the proxy 
  61.  * instance, a <code>java.lang.reflect.Method</code> object identifying 
  62.  * the method that was invoked, and an array of type <code>Object</code> 
  63.  * containing the arguments.  The invocation handler processes the 
  64.  * encoded method invocation as appropriate and the result that it 
  65.  * returns will be returned as the result of the method invocation on 
  66.  * the proxy instance. 
  67.  * 
  68.  * <p>A proxy class has the following properties: 
  69.  * 
  70.  * <ul> 
  71.  * <li>Proxy classes are public, final, and not abstract. 
  72.  * 
  73.  * <li>The unqualified name of a proxy class is unspecified.  The space 
  74.  * of class names that begin with the string <code>"$Proxy"</code> 
  75.  * should be, however, reserved for proxy classes. 
  76.  * 
  77.  * <li>A proxy class extends <code>java.lang.reflect.Proxy</code>. 
  78.  * 
  79.  * <li>A proxy class implements exactly the interfaces specified at its 
  80.  * creation, in the same order. 
  81.  * 
  82.  * <li>If a proxy class implements a non-public interface, then it will 
  83.  * be defined in the same package as that interface.  Otherwise, the 
  84.  * package of a proxy class is also unspecified.  Note that package 
  85.  * sealing will not prevent a proxy class from being successfully defined 
  86.  * in a particular package at runtime, and neither will classes already 
  87.  * defined by the same class loader and the same package with particular 
  88.  * signers. 
  89.  * 
  90.  * <li>Since a proxy class implements all of the interfaces specified at 
  91.  * its creation, invoking <code>getInterfaces</code> on its 
  92.  * <code>Class</code> object will return an array containing the same 
  93.  * list of interfaces (in the order specified at its creation), invoking 
  94.  * <code>getMethods</code> on its <code>Class</code> object will return 
  95.  * an array of <code>Method</code> objects that include all of the 
  96.  * methods in those interfaces, and invoking <code>getMethod</code> will 
  97.  * find methods in the proxy interfaces as would be expected. 
  98.  * 
  99.  * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method will 
  100.  * return true if it is passed a proxy class-- a class returned by 
  101.  * <code>Proxy.getProxyClass</code> or the class of an object returned by 
  102.  * <code>Proxy.newProxyInstance</code>-- and false otherwise. 
  103.  * 
  104.  * <li>The <code>java.security.ProtectionDomain</code> of a proxy class 
  105.  * is the same as that of system classes loaded by the bootstrap class 
  106.  * loader, such as <code>java.lang.Object</code>, because the code for a 
  107.  * proxy class is generated by trusted system code.  This protection 
  108.  * domain will typically be granted 
  109.  * <code>java.security.AllPermission</code>. 
  110.  * 
  111.  * <li>Each proxy class has one public constructor that takes one argument, 
  112.  * an implementation of the interface {@link InvocationHandler}, to set 
  113.  * the invocation handler for a proxy instance.  Rather than having to use 
  114.  * the reflection API to access the public constructor, a proxy instance 
  115.  * can be also be created by calling the {@link Proxy#newProxyInstance 
  116.  * Proxy.newInstance} method, which combines the actions of calling 
  117.  * {@link Proxy#getProxyClass Proxy.getProxyClass} with invoking the 
  118.  * constructor with an invocation handler. 
  119.  * </ul> 
  120.  * 
  121.  * <p>A proxy instance has the following properties: 
  122.  * 
  123.  * <ul> 
  124.  * <li>Given a proxy instance <code>proxy</code> and one of the 
  125.  * interfaces implemented by its proxy class <code>Foo</code>, the 
  126.  * following expression will return true: 
  127.  * <pre> 
  128.  *     <code>proxy instanceof Foo</code> 
  129.  * </pre> 
  130.  * and the following cast operation will succeed (rather than throwing 
  131.  * a <code>ClassCastException</code>): 
  132.  * <pre> 
  133.  *     <code>(Foo) proxy</code> 
  134.  * </pre> 
  135.  * 
  136.  * <li>Each proxy instance has an associated invocation handler, the one 
  137.  * that was passed to its constructor.  The static 
  138.  * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method 
  139.  * will return the invocation handler associated with the proxy instance 
  140.  * passed as its argument. 
  141.  * 
  142.  * <li>An interface method invocation on a proxy instance will be 
  143.  * encoded and dispatched to the invocation handler's {@link 
  144.  * InvocationHandler#invoke invoke} method as described in the 
  145.  * documentation for that method. 
  146.  * 
  147.  * <li>An invocation of the <code>hashCode</code>, 
  148.  * <code>equals</code>, or <code>toString</code> methods declared in 
  149.  * <code>java.lang.Object</code> on a proxy instance will be encoded and 
  150.  * dispatched to the invocation handler's <code>invoke</code> method in 
  151.  * the same manner as interface method invocations are encoded and 
  152.  * dispatched, as described above.  The declaring class of the 
  153.  * <code>Method</code> object passed to <code>invoke</code> will be 
  154.  * <code>java.lang.Object</code>.  Other public methods of a proxy 
  155.  * instance inherited from <code>java.lang.Object</code> are not 
  156.  * overridden by a proxy class, so invocations of those methods behave 
  157.  * like they do for instances of <code>java.lang.Object</code>. 
  158.  * </ul> 
  159.  * 
  160.  * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3> 
  161.  * 
  162.  * <p>When two or more interfaces of a proxy class contain a method with 
  163.  * the same name and parameter signature, the order of the proxy class's 
  164.  * interfaces becomes significant.  When such a <i>duplicate method</i> 
  165.  * is invoked on a proxy instance, the <code>Method</code> object passed 
  166.  * to the invocation handler will not necessarily be the one whose 
  167.  * declaring class is assignable from the reference type of the interface 
  168.  * that the proxy's method was invoked through.  This limitation exists 
  169.  * because the corresponding method implementation in the generated proxy 
  170.  * class cannot determine which interface it was invoked through. 
  171.  * Therefore, when a duplicate method is invoked on a proxy instance, 
  172.  * the <code>Method</code> object for the method in the foremost interface 
  173.  * that contains the method (either directly or inherited through a 
  174.  * superinterface) in the proxy class's list of interfaces is passed to 
  175.  * the invocation handler's <code>invoke</code> method, regardless of the 
  176.  * reference type through which the method invocation occurred. 
  177.  * 
  178.  * <p>If a proxy interface contains a method with the same name and 
  179.  * parameter signature as the <code>hashCode</code>, <code>equals</code>, 
  180.  * or <code>toString</code> methods of <code>java.lang.Object</code>, 
  181.  * when such a method is invoked on a proxy instance, the 
  182.  * <code>Method</code> object passed to the invocation handler will have 
  183.  * <code>java.lang.Object</code> as its declaring class.  In other words, 
  184.  * the public, non-final methods of <code>java.lang.Object</code> 
  185.  * logically precede all of the proxy interfaces for the determination of 
  186.  * which <code>Method</code> object to pass to the invocation handler. 
  187.  * 
  188.  * <p>Note also that when a duplicate method is dispatched to an 
  189.  * invocation handler, the <code>invoke</code> method may only throw 
  190.  * checked exception types that are assignable to one of the exception 
  191.  * types in the <code>throws</code> clause of the method in <i>all</i> of 
  192.  * the proxy interfaces that it can be invoked through.  If the 
  193.  * <code>invoke</code> method throws a checked exception that is not 
  194.  * assignable to any of the exception types declared by the method in one 
  195.  * of the proxy interfaces that it can be invoked through, then an 
  196.  * unchecked <code>UndeclaredThrowableException</code> will be thrown by 
  197.  * the invocation on the proxy instance.  This restriction means that not 
  198.  * all of the exception types returned by invoking 
  199.  * <code>getExceptionTypes</code> on the <code>Method</code> object 
  200.  * passed to the <code>invoke</code> method can necessarily be thrown 
  201.  * successfully by the <code>invoke</code> method. 
  202.  * 
  203.  * @author  Peter Jones 
  204.  * @version %I%, %E% 
  205.  * @see     InvocationHandler 
  206.  * @since   1.3 
  207.  */  
  208. public class Proxy implements java.io.Serializable {  
  209.   
  210.     private static final long serialVersionUID = -2222568056686623797L;  
  211.   
  212.     /** prefix for all proxy class names */  
  213.     private final static String proxyClassNamePrefix = "$Proxy";  
  214.   
  215.     /** parameter types of a proxy class constructor */  
  216.     private final static Class[] constructorParams =  
  217.     { InvocationHandler.class };  
  218.   
  219.     /** maps a class loader to the proxy class cache for that loader */  
  220.     private static Map loaderToCache = new WeakHashMap();  
  221.   
  222.     /** marks that a particular proxy class is currently being generated */  
  223.     private static Object pendingGenerationMarker = new Object();  
  224.   
  225.     /** next number to use for generation of unique proxy class names */  
  226.     private static long nextUniqueNumber = 0;  
  227.     private static Object nextUniqueNumberLock = new Object();  
  228.   
  229.     /** set of all generated proxy classes, for isProxyClass implementation */  
  230.     private static Map proxyClasses =  
  231.     Collections.synchronizedMap(new WeakHashMap());  
  232.   
  233.     /** 
  234.      * the invocation handler for this proxy instance. 
  235.      * @serial 
  236.      */  
  237.     protected InvocationHandler h;  
  238.   
  239.     /** 
  240.      * Prohibits instantiation. 
  241.      */  
  242.     private Proxy() {  
  243.     }  
  244.   
  245.     /** 
  246.      * Constructs a new <code>Proxy</code> instance from a subclass 
  247.      * (typically, a dynamic proxy class) with the specified value 
  248.      * for its invocation handler. 
  249.      * 
  250.      * @param   h the invocation handler for this proxy instance 
  251.      */  
  252.     protected Proxy(InvocationHandler h) {  
  253.         doNewInstanceCheck();  
  254.     this.h = h;  
  255.     }  
  256.   
  257.     private static class ProxyAccessHelper {  
  258.         // The permission is implementation specific.  
  259.         static final Permission PROXY_PERMISSION =  
  260.             new ReflectPermission("proxyConstructorNewInstance");  
  261.         // These system properties are defined to provide a short-term  
  262.         // workaround if customers need to disable the new security checks.  
  263.         static final boolean allowNewInstance;  
  264.         static final boolean allowNullLoader;  
  265.         static {  
  266.             allowNewInstance = getBooleanProperty("sun.reflect.proxy.allowsNewInstance");  
  267.             allowNullLoader = getBooleanProperty("sun.reflect.proxy.allowsNullLoader");  
  268.         }  
  269.    
  270.         private static boolean getBooleanProperty(final String key) {  
  271.             String s = AccessController.doPrivileged(new PrivilegedAction<String>() {  
  272.                 public String run() {  
  273.                     return System.getProperty(key);  
  274.                 }  
  275.             });  
  276.             return Boolean.valueOf(s);  
  277.         }  
  278.    
  279.         static boolean needsNewInstanceCheck(Class<?> proxyClass) {  
  280.             if (!Proxy.isProxyClass(proxyClass) || allowNewInstance) {  
  281.                 return false;  
  282.             }  
  283.    
  284.             if (proxyClass.getName().startsWith(ReflectUtil.PROXY_PACKAGE + ".")) {  
  285.                 // all proxy interfaces are public  
  286.                 return false;  
  287.             }  
  288.             for (Class<?> intf : proxyClass.getInterfaces()) {  
  289.                 if (!Modifier.isPublic(intf.getModifiers())) {  
  290.                     return true;  
  291.                 }  
  292.             }  
  293.             return false;  
  294.         }  
  295.     }  
  296.    
  297.     /* 
  298.      * Access check on a proxy class that implements any non-public interface. 
  299.      * 
  300.      * @throws  SecurityException if a security manager exists, and 
  301.      *          the caller does not have the permission. 
  302.      */  
  303.     private void doNewInstanceCheck() {  
  304.         SecurityManager sm = System.getSecurityManager();  
  305.         Class<?> proxyClass = this.getClass();  
  306.         if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(proxyClass)) {  
  307.             try {  
  308.                 sm.checkPermission(ProxyAccessHelper.PROXY_PERMISSION);  
  309.             } catch (SecurityException e) {  
  310.                 throw new SecurityException("Not allowed to construct a Proxy "  
  311.                         + "instance that implements a non-public interface", e);  
  312.             }  
  313.         }  
  314.     }  
  315.   
  316.     /** 
  317.      * Returns the <code>java.lang.Class</code> object for a proxy class 
  318.      * given a class loader and an array of interfaces.  The proxy class 
  319.      * will be defined by the specified class loader and will implement 
  320.      * all of the supplied interfaces.  If a proxy class for the same 
  321.      * permutation of interfaces has already been defined by the class 
  322.      * loader, then the existing proxy class will be returned; otherwise, 
  323.      * a proxy class for those interfaces will be generated dynamically 
  324.      * and defined by the class loader. 
  325.      * 
  326.      * <p>There are several restrictions on the parameters that may be 
  327.      * passed to <code>Proxy.getProxyClass</code>: 
  328.      * 
  329.      * <ul> 
  330.      * <li>All of the <code>Class</code> objects in the 
  331.      * <code>interfaces</code> array must represent interfaces, not 
  332.      * classes or primitive types. 
  333.      * 
  334.      * <li>No two elements in the <code>interfaces</code> array may 
  335.      * refer to identical <code>Class</code> objects. 
  336.      * 
  337.      * <li>All of the interface types must be visible by name through the 
  338.      * specified class loader.  In other words, for class loader 
  339.      * <code>cl</code> and every interface <code>i</code>, the following 
  340.      * expression must be true: 
  341.      * <pre> 
  342.      *     Class.forName(i.getName(), false, cl) == i 
  343.      * </pre> 
  344.      * 
  345.      * <li>All non-public interfaces must be in the same package; 
  346.      * otherwise, it would not be possible for the proxy class to 
  347.      * implement all of the interfaces, regardless of what package it is 
  348.      * defined in. 
  349.      * 
  350.      * <li>For any set of member methods of the specified interfaces 
  351.      * that have the same signature: 
  352.      * <ul> 
  353.      * <li>If the return type of any of the methods is a primitive 
  354.      * type or void, then all of the methods must have that same 
  355.      * return type. 
  356.      * <li>Otherwise, one of the methods must have a return type that 
  357.      * is assignable to all of the return types of the rest of the 
  358.      * methods. 
  359.      * </ul> 
  360.      * 
  361.      * <li>The resulting proxy class must not exceed any limits imposed 
  362.      * on classes by the virtual machine.  For example, the VM may limit 
  363.      * the number of interfaces that a class may implement to 65535; in 
  364.      * that case, the size of the <code>interfaces</code> array must not 
  365.      * exceed 65535. 
  366.      * </ul> 
  367.      * 
  368.      * <p>If any of these restrictions are violated, 
  369.      * <code>Proxy.getProxyClass</code> will throw an 
  370.      * <code>IllegalArgumentException</code>.  If the <code>interfaces</code> 
  371.      * array argument or any of its elements are <code>null</code>, a 
  372.      * <code>NullPointerException</code> will be thrown. 
  373.      * 
  374.      * <p>Note that the order of the specified proxy interfaces is 
  375.      * significant: two requests for a proxy class with the same combination 
  376.      * of interfaces but in a different order will result in two distinct 
  377.      * proxy classes. 
  378.      * 
  379.      * @param   loader the class loader to define the proxy class 
  380.      * @param   interfaces the list of interfaces for the proxy class 
  381.      *      to implement 
  382.      * @return  a proxy class that is defined in the specified class loader 
  383.      *      and that implements the specified interfaces 
  384.      * @throws  IllegalArgumentException if any of the restrictions on the 
  385.      *      parameters that may be passed to <code>getProxyClass</code> 
  386.      *      are violated 
  387.      * @throws  NullPointerException if the <code>interfaces</code> array 
  388.      *      argument or any of its elements are <code>null</code> 
  389.      */  
  390.     public static Class<?> getProxyClass(ClassLoader loader,   
  391.                                          Class<?>... interfaces)  
  392.     throws IllegalArgumentException  
  393.     {  
  394.         return getProxyClass0(loader, interfaces); // stack walk magic: do not refactor  
  395.     }  
  396.   
  397.     private static void checkProxyLoader(ClassLoader ccl,  
  398.                                          ClassLoader loader)  
  399.     {  
  400.         SecurityManager sm = System.getSecurityManager();  
  401.         if (sm != null) {  
  402.             if (loader == null && ccl != null) {  
  403.                 if (!ProxyAccessHelper.allowNullLoader) {  
  404.                     sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);  
  405.                 }  
  406.             }  
  407.         }  
  408.     }  
  409.    
  410.     /* 
  411.      * Generate a proxy class (caller-sensitive). 
  412.      * 
  413.      * To define a proxy class, it performs the access checks as in 
  414.      * Class.forName (VM will invoke ClassLoader.checkPackageAccess): 
  415.      * 1. "getClassLoader" permission check if loader == null 
  416.      * 2. checkPackageAccess on the interfaces it implements 
  417.      * 
  418.      * To get a constructor and new instance of a proxy class, it performs 
  419.      * the package access check on the interfaces it implements 
  420.      * as in Class.getConstructor. 
  421.      * 
  422.      * If an interface is non-public, the proxy class must be defined by 
  423.      * the defining loader of the interface.  If the caller's class loader 
  424.      * is not the same as the defining loader of the interface, the VM 
  425.      * will throw IllegalAccessError when the generated proxy class is 
  426.      * being defined via the defineClass0 method. 
  427.      */  
  428.     private static Class<?> getProxyClass0(ClassLoader loader,  
  429.                                            Class<?>... interfaces) {  
  430.         SecurityManager sm = System.getSecurityManager();  
  431.         if (sm != null) {  
  432.             final int CALLER_FRAME = 3// 0: Reflection, 1: getProxyClass0 2: Proxy 3: caller  
  433.             final Class<?> caller = Reflection.getCallerClass(CALLER_FRAME);  
  434.             final ClassLoader ccl = caller.getClassLoader();  
  435.             checkProxyLoader(ccl, loader);  
  436.             ReflectUtil.checkProxyPackageAccess(ccl, interfaces);  
  437.         }  
  438.         if (interfaces.length > 65535) {  
  439.         throw new IllegalArgumentException("interface limit exceeded");  
  440.     }  
  441.   
  442.     Class proxyClass = null;  
  443.   
  444.     /* collect interface names to use as key for proxy class cache */  
  445.     String[] interfaceNames = new String[interfaces.length];  
  446.   
  447.     Set interfaceSet = new HashSet();   // for detecting duplicates  
  448.   
  449.     for (int i = 0; i < interfaces.length; i++) {  
  450.         /* 
  451.          * Verify that the class loader resolves the name of this 
  452.          * interface to the same Class object. 
  453.          */  
  454.         String interfaceName = interfaces[i].getName();  
  455.         Class interfaceClass = null;  
  456.         try {  
  457.         interfaceClass = Class.forName(interfaceName, false, loader);  
  458.         } catch (ClassNotFoundException e) {  
  459.         }  
  460.         if (interfaceClass != interfaces[i]) {  
  461.         throw new IllegalArgumentException(  
  462.             interfaces[i] + " is not visible from class loader");  
  463.         }  
  464.   
  465.         /* 
  466.          * Verify that the Class object actually represents an 
  467.          * interface. 
  468.          */  
  469.         if (!interfaceClass.isInterface()) {  
  470.         throw new IllegalArgumentException(  
  471.             interfaceClass.getName() + " is not an interface");  
  472.         }  
  473.   
  474.         /* 
  475.          * Verify that this interface is not a duplicate. 
  476.          */  
  477.         if (interfaceSet.contains(interfaceClass)) {  
  478.         throw new IllegalArgumentException(  
  479.             "repeated interface: " + interfaceClass.getName());  
  480.         }  
  481.         interfaceSet.add(interfaceClass);  
  482.   
  483.         interfaceNames[i] = interfaceName;  
  484.     }  
  485.   
  486.     /* 
  487.      * Using string representations of the proxy interfaces as 
  488.      * keys in the proxy class cache (instead of their Class 
  489.      * objects) is sufficient because we require the proxy 
  490.      * interfaces to be resolvable by name through the supplied 
  491.      * class loader, and it has the advantage that using a string 
  492.      * representation of a class makes for an implicit weak 
  493.      * reference to the class. 
  494.      */  
  495.     Object key = Arrays.asList(interfaceNames);  
  496.   
  497.     /* 
  498.      * Find or create the proxy class cache for the class loader. 
  499.      */  
  500.     Map cache;  
  501.     synchronized (loaderToCache) {  
  502.         cache = (Map) loaderToCache.get(loader);  
  503.         if (cache == null) {  
  504.         cache = new HashMap();  
  505.         loaderToCache.put(loader, cache);  
  506.         }  
  507.         /* 
  508.          * This mapping will remain valid for the duration of this 
  509.          * method, without further synchronization, because the mapping 
  510.          * will only be removed if the class loader becomes unreachable. 
  511.          */  
  512.     }  
  513.   
  514.     /* 
  515.      * Look up the list of interfaces in the proxy class cache using 
  516.      * the key.  This lookup will result in one of three possible 
  517.      * kinds of values: 
  518.      *     null, if there is currently no proxy class for the list of 
  519.      *         interfaces in the class loader, 
  520.      *     the pendingGenerationMarker object, if a proxy class for the 
  521.      *         list of interfaces is currently being generated, 
  522.      *     or a weak reference to a Class object, if a proxy class for 
  523.      *         the list of interfaces has already been generated. 
  524.      */  
  525.     synchronized (cache) {  
  526.         /* 
  527.          * Note that we need not worry about reaping the cache for 
  528.          * entries with cleared weak references because if a proxy class 
  529.          * has been garbage collected, its class loader will have been 
  530.          * garbage collected as well, so the entire cache will be reaped 
  531.          * from the loaderToCache map. 
  532.          */  
  533.         do {  
  534.         Object value = cache.get(key);  
  535.         if (value instanceof Reference) {  
  536.             proxyClass = (Class) ((Reference) value).get();  
  537.         }  
  538.         if (proxyClass != null) {  
  539.             // proxy class already generated: return it  
  540.             return proxyClass;  
  541.         } else if (value == pendingGenerationMarker) {  
  542.             // proxy class being generated: wait for it  
  543.             try {  
  544.             cache.wait();  
  545.             } catch (InterruptedException e) {  
  546.             /* 
  547.              * The class generation that we are waiting for should 
  548.              * take a small, bounded time, so we can safely ignore 
  549.              * thread interrupts here. 
  550.              */  
  551.             }  
  552.             continue;  
  553.         } else {  
  554.             /* 
  555.              * No proxy class for this list of interfaces has been 
  556.              * generated or is being generated, so we will go and 
  557.              * generate it now.  Mark it as pending generation. 
  558.              */  
  559.             cache.put(key, pendingGenerationMarker);  
  560.             break;  
  561.         }  
  562.         } while (true);  
  563.     }  
  564.   
  565.     try {  
  566.         String proxyPkg = null// package to define proxy class in  
  567.   
  568.         /* 
  569.          * Record the package of a non-public proxy interface so that the 
  570.          * proxy class will be defined in the same package.  Verify that 
  571.          * all non-public proxy interfaces are in the same package. 
  572.          */  
  573.         for (int i = 0; i < interfaces.length; i++) {  
  574.         int flags = interfaces[i].getModifiers();  
  575.         if (!Modifier.isPublic(flags)) {  
  576.             String name = interfaces[i].getName();  
  577.             int n = name.lastIndexOf('.');  
  578.             String pkg = ((n == -1) ? "" : name.substring(0, n + 1));  
  579.             if (proxyPkg == null) {  
  580.             proxyPkg = pkg;  
  581.             } else if (!pkg.equals(proxyPkg)) {  
  582.             throw new IllegalArgumentException(  
  583.                 "non-public interfaces from different packages");  
  584.             }  
  585.         }  
  586.         }  
  587.   
  588.             if (proxyPkg == null) {  
  589.                 // if no non-public proxy interfaces, use com.sun.proxy package  
  590.                 proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";  
  591.         }  
  592.   
  593.         {  
  594.         /* 
  595.          * Choose a name for the proxy class to generate. 
  596.          */  
  597.         long num;  
  598.         synchronized (nextUniqueNumberLock) {  
  599.             num = nextUniqueNumber++;  
  600.         }  
  601.         String proxyName = proxyPkg + proxyClassNamePrefix + num;  
  602.         /* 
  603.          * Verify that the class loader hasn't already 
  604.          * defined a class with the chosen name. 
  605.          */  
  606.   
  607.         /* 
  608.          * Generate the specified proxy class. 
  609.          */  
  610.         byte[] proxyClassFile = ProxyGenerator.generateProxyClass(  
  611.             proxyName, interfaces);  
  612.         try {  
  613.             proxyClass = defineClass0(loader, proxyName,  
  614.             proxyClassFile, 0, proxyClassFile.length);  
  615.         } catch (ClassFormatError e) {  
  616.             /* 
  617.              * A ClassFormatError here means that (barring bugs in the 
  618.              * proxy class generation code) there was some other 
  619.              * invalid aspect of the arguments supplied to the proxy 
  620.              * class creation (such as virtual machine limitations 
  621.              * exceeded). 
  622.              */  
  623.             throw new IllegalArgumentException(e.toString());  
  624.         }  
  625.         }  
  626.         // add to set of all generated proxy classes, for isProxyClass  
  627.         proxyClasses.put(proxyClass, null);  
  628.   
  629.     } finally {  
  630.         /* 
  631.          * We must clean up the "pending generation" state of the proxy 
  632.          * class cache entry somehow.  If a proxy class was successfully 
  633.          * generated, store it in the cache (with a weak reference); 
  634.          * otherwise, remove the reserved entry.  In all cases, notify 
  635.          * all waiters on reserved entries in this cache. 
  636.          */  
  637.         synchronized (cache) {  
  638.         if (proxyClass != null) {  
  639.             cache.put(key, new WeakReference(proxyClass));  
  640.         } else {  
  641.             cache.remove(key);  
  642.         }  
  643.         cache.notifyAll();  
  644.         }  
  645.     }  
  646.     return proxyClass;  
  647.     }  
  648.   
  649.     /** 
  650.      * Returns an instance of a proxy class for the specified interfaces 
  651.      * that dispatches method invocations to the specified invocation 
  652.      * handler.  This method is equivalent to: 
  653.      * <pre> 
  654.      *     Proxy.getProxyClass(loader, interfaces). 
  655.      *         getConstructor(new Class[] { InvocationHandler.class }). 
  656.      *         newInstance(new Object[] { handler }); 
  657.      * </pre> 
  658.      * 
  659.      * <p><code>Proxy.newProxyInstance</code> throws 
  660.      * <code>IllegalArgumentException</code> for the same reasons that 
  661.      * <code>Proxy.getProxyClass</code> does. 
  662.      * 
  663.      * @param   loader the class loader to define the proxy class 
  664.      * @param   interfaces the list of interfaces for the proxy class 
  665.      *      to implement 
  666.      * @param   h the invocation handler to dispatch method invocations to 
  667.      * @return  a proxy instance with the specified invocation handler of a 
  668.      *      proxy class that is defined by the specified class loader 
  669.      *      and that implements the specified interfaces 
  670.      * @throws  IllegalArgumentException if any of the restrictions on the 
  671.      *      parameters that may be passed to <code>getProxyClass</code> 
  672.      *      are violated 
  673.      * @throws  NullPointerException if the <code>interfaces</code> array 
  674.      *      argument or any of its elements are <code>null</code>, or 
  675.      *      if the invocation handler, <code>h</code>, is 
  676.      *      <code>null</code> 
  677.      */  
  678.     public static Object newProxyInstance(ClassLoader loader,  
  679.                       Class<?>[] interfaces,  
  680.                       InvocationHandler h)  
  681.     throws IllegalArgumentException  
  682.     {  
  683.     if (h == null) {  
  684.         throw new NullPointerException();  
  685.     }  
  686.   
  687.     /* 
  688.      * Look up or generate the designated proxy class. 
  689.      */  
  690.         Class<?> cl = getProxyClass0(loader, interfaces); // stack walk magic: do not refactor  
  691.   
  692.     /* 
  693.      * Invoke its constructor with the designated invocation handler. 
  694.      */  
  695.     try {  
  696.             final Constructor<?> cons = cl.getConstructor(constructorParams);  
  697.             final InvocationHandler ih = h;  
  698.             SecurityManager sm = System.getSecurityManager();  
  699.             if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {  
  700.                 // create proxy instance with doPrivilege as the proxy class may  
  701.                 // implement non-public interfaces that requires a special permission  
  702.                 return AccessController.doPrivileged(new PrivilegedAction<Object>() {  
  703.                     public Object run() {  
  704.                         return newInstance(cons, ih);  
  705.                     }  
  706.                 });  
  707.             } else {  
  708.                 return newInstance(cons, ih);  
  709.             }  
  710.     } catch (NoSuchMethodException e) {  
  711.         throw new InternalError(e.toString());  
  712.     }   
  713.     }  
  714.   
  715.     private static Object newInstance(Constructor<?> cons, InvocationHandler h) {  
  716.         try {  
  717.             return cons.newInstance(new Object[] {h} );  
  718.         } catch (IllegalAccessException e) {  
  719.             throw new InternalError(e.toString());  
  720.         } catch (InstantiationException e) {  
  721.             throw new InternalError(e.toString());  
  722.         } catch (InvocationTargetException e) {  
  723.             Throwable t = e.getCause();  
  724.             if (t instanceof RuntimeException) {  
  725.                 throw (RuntimeException) t;  
  726.             } else {  
  727.                 throw new InternalError(t.toString());  
  728.             }  
  729.         }  
  730.     }  
  731.   
  732.     /** 
  733.      * Returns true if and only if the specified class was dynamically 
  734.      * generated to be a proxy class using the <code>getProxyClass</code> 
  735.      * method or the <code>newProxyInstance</code> method. 
  736.      * 
  737.      * <p>The reliability of this method is important for the ability 
  738.      * to use it to make security decisions, so its implementation should 
  739.      * not just test if the class in question extends <code>Proxy</code>. 
  740.      * 
  741.      * @param   cl the class to test 
  742.      * @return  <code>true</code> if the class is a proxy class and 
  743.      *      <code>false</code> otherwise 
  744.      * @throws  NullPointerException if <code>cl</code> is <code>null</code> 
  745.      */  
  746.     public static boolean isProxyClass(Class<?> cl) {  
  747.     if (cl == null) {  
  748.         throw new NullPointerException();  
  749.     }  
  750.   
  751.     return proxyClasses.containsKey(cl);  
  752.     }  
  753.   
  754.     /** 
  755.      * Returns the invocation handler for the specified proxy instance. 
  756.      * 
  757.      * @param   proxy the proxy instance to return the invocation handler for 
  758.      * @return  the invocation handler for the proxy instance 
  759.      * @throws  IllegalArgumentException if the argument is not a 
  760.      *      proxy instance 
  761.      */  
  762.     public static InvocationHandler getInvocationHandler(Object proxy)  
  763.     throws IllegalArgumentException  
  764.     {  
  765.     /* 
  766.      * Verify that the object is actually a proxy instance. 
  767.      */  
  768.     if (!isProxyClass(proxy.getClass())) {  
  769.         throw new IllegalArgumentException("not a proxy instance");  
  770.     }  
  771.   
  772.     Proxy p = (Proxy) proxy;  
  773.     return p.h;  
  774.     }  
  775.   
  776.     private static native Class defineClass0(ClassLoader loader, String name,  
  777.                          byte[] b, int off, int len);  
  778. }  


0 0
原创粉丝点击