我们可以使用Proxy.newProxyInstance来创建动态代理类实例,或者使用Proxy.getProxyClass()获取代理类对象再反射的方式来创建,下面我们以com.anbai.sec.proxy.FileSystem接口为例,演示如何创建其动态代理类实例。
Proxy.newProxyInstance示例代码:
// 创建UnixFileSystem类实例FileSystem fileSystem = new UnixFileSystem();// 使用JDK动态代理生成FileSystem动态代理类实例FileSystem proxyInstance = (FileSystem) Proxy.newProxyInstance(FileSystem.class.getClassLoader(),// 指定动态代理类的类加载器new Class[]{FileSystem.class}, // 定义动态代理生成的类实现的接口new JDKInvocationHandler(fileSystem)// 动态代理处理类);
Proxy.getProxyClass反射示例代码:
// 创建UnixFileSystem类实例FileSystem fileSystem = new UnixFileSystem();// 创建动态代理处理类InvocationHandler handler = new JDKInvocationHandler(fileSystem);// 通过指定类加载器、类实现的接口数组生成一个动态代理类Class proxyClass = Proxy.getProxyClass(FileSystem.class.getClassLoader(),// 指定动态代理类的类加载器new Class[]{FileSystem.class}// 定义动态代理生成的类实现的接口);// 使用反射获取Proxy类构造器并创建动态代理类实例FileSystem proxyInstance = (FileSystem) proxyClass.getConstructor(new Class[]{InvocationHandler.class}).newInstance(new Object[]{handler});
