java动态代理模拟实现【学习】
1.概念免了,直接贴核心代码
ProxyWithMe.java
package com.learn.proxyimp.interfaces; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import org.apache.commons.io.FileUtils; import org.proxydemo.interfaces.HelloWorld; import com.learn.proxyimp.classloads.MyClassLoader; /*** * 1.动态生成java动态代理类 extends 此类 implements接口 2.将动态生成的代理加载到JVM * * * 3.实例化代理对象,返回 * * @author pengjf * */ public class ProxyWithMe { private static String splitStr = "\r\n"; protected InvocationHandlerByMe h; public static Object newProxyInstance(MyClassLoader loader, Class> interfaces, InvocationHandlerByMe handle) throws Exception { /*** * 1.如果动态核心处理类为空,直接抛出空指针异常,作用:此对象赋值给动态生成的代理类的属性,也就是:InvocationHandlerByMe h */ if (handle == null) { throw new NullPointerException(); } /** * 2.根据类加载器,以及接口,动态生成代理类,此则是核心关键中的关键 */ Class> cl = getProxyClass(loader, interfaces); /* * Invoke its constructor with the designated invocation handler. */ try { // 调用代理对象的构造方法(也就是$Proxy0(InvocationHandler h)) Constructor> cons = cl.getConstructor(InvocationHandlerByMe.class); // 生成代理类的实例并把MyInvocationHandler的实例传给它的构造方法 return (Object) cons.newInstance(new Object[] { handle }); } 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()); } } /*** * 根据类加载器,以及接口,动态生成代理类,此则是核心关键中的关键 * * @param handle * @param loader * @param interfaces * @return * @throws IOException * @throws ClassNotFoundException */ private static Class> getProxyClass(MyClassLoader loader, Class> interfaces) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("package com.learn.dynproxy;").append(splitStr); sb.append("import java.lang.reflect.Method;").append(splitStr); sb.append("public class $Proxy0 extends ").append(ProxyWithMe.class.getName()).append(" implements ") .append(interfaces.getName()).append(splitStr); sb.append("{").append(splitStr).append(splitStr); // 1.先把构造器覆盖了,主要给InvocationHandler赋值 sb.append("public $Proxy0(").append(InvocationHandlerByMe.class.getName() + " h){").append(splitStr); sb.append(" this.h=h;").append(splitStr); sb.append("}").append(splitStr); // 2.重写接口方法 // 只重写public的方法 for (Method method : interfaces.getMethods()) { // public String say(String mst){} if (method.getModifiers() == (Modifier.PUBLIC | Modifier.ABSTRACT)) {// 抽象的 sb.append("public ").append(method.getReturnType().getName()).append(" ").append(method.getName()) .append("("); String paramType = "new Class[] {"; String paramVal = "new Object[] {"; Class>[] czzs = method.getParameterTypes(); for (int i = 0; i < czzs.length; i++) { sb.append(czzs[i].getName() + " " + "args" + i); paramVal += "args" + i; paramType += czzs[i].getName() + ".class"; if (i != czzs.length - 1) { sb.append(","); paramType += ","; paramVal += ","; } } paramType += "}"; paramVal += "}"; sb.append("){").append(splitStr); // 3.代码此处进行其实调用我们h的方法,因为在实例的过过程:将将handle赋值,handle中再new会把用户真实的对象的传递过来,将相当于调用handle的方法 // handle就相当于我们拦截前后做的具体的事情 // invoke(Object proxyObject, Method method, Object[] args) // 定义Method的方法 // Method meth = cls.getMethod("say", new Class[] { String.class }); sb.append("try{").append(splitStr); sb.append("Class> temp=Class.forName(\"" + interfaces.getName() + "\")").append(";").append(splitStr); sb.append("Method method=temp.getMethod(\"" + method.getName() + "\"," + paramType + ")").append(";") .append(splitStr); //需要针对类型去做处理 if(method.getReturnType().getName().equals("void")) { sb.append("h.invoke(this,method," + paramVal + ")").append(";").append(splitStr); }else { sb.append("Object object=h.invoke(this,method," + paramVal + ")").append(";").append(splitStr); sb.append("return (" + method.getReturnType().getName() + ") object").append(";").append(splitStr); } sb.append(" } catch (Throwable e) {"); sb.append("e.printStackTrace();"); sb.append("}"); if(!method.getReturnType().getName().equals("void")) { sb.append("return null;").append(splitStr); } sb.append("}").append(splitStr); } } sb.append("}"); // target\classes\com\learn\dynproxy String filename = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/" + "com" + "/" + "learn" + "/" + "dynproxy" + "/" + "$Proxy0.java"; File file = new File(filename); // 使用org.apache.commons.io.FileUtils.writeStringToFile()将源码写入磁盘 // 编写到处,可以运行一下程序,可以在当前目录中看到生成的.java文件 FileUtils.writeStringToFile(file, sb.toString(), "utf-8"); // 获得当前系统中的编译器 JavaCompiler complier = ToolProvider.getSystemJavaCompiler(); // 获得文件管理者 StandardJavaFileManager fileMgr = complier.getStandardFileManager(null, null, null); Iterable its = fileMgr.getJavaFileObjects(filename); // 编译任务 JavaCompiler.CompilationTask task = complier.getTask(null, fileMgr, null, null, null, its); // 开始编译,执行完可在当前目录下看到.class文件 task.call(); fileMgr.close(); // load到内存 return loader.loadClass("com.learn.dynproxy.$Proxy0"); } public static void main(String[] args) throws Exception { // 使用反射第一步:获取操作类MethodDemoFieldDemo所对应的Class对象 Class> cls = HelloWorld.class; // 使用MethodDemo类的class对象生成 实例 // 获取public int addResult(int addNum)方法 Method addMethod = cls.getMethod("say", new Class[] { String.class }); System.out.println("修饰符: " + Modifier.toString(addMethod.getModifiers())); System.out.println("返回值: " + addMethod.getReturnType()); System.out.println("方法名称: " + addMethod.getName()); System.out.println("参数列表: " + addMethod.getParameterTypes()[0]); System.out.println(addMethod.getParameterTypes() + "hello"); } }
分析都在图片中
InvocationHandlerByMeImpl.java
package com.learn.proxyimp.interfaces.impls; import java.lang.reflect.Method; import com.learn.proxyimp.interfaces.InvocationHandlerByMe; public class InvocationHandlerByMeImpl implements InvocationHandlerByMe{ private Object object;//被代理的对象 public InvocationHandlerByMeImpl(Object object) { this.object=object; } public Object invoke(Object proxyObject, Method method, Object[] args) throws Throwable { //此处通过传递object对象,被代理的对象,调用自己的方法,然后再牵头就可以做相关的事情了 System.out.println("==============被代理了======="); System.out.println("==============执行前======="); Object result=method.invoke(object, args); System.out.println("==============执行后======="); return result; } }
生成的动态代理
package com.learn.dynproxy; import java.lang.reflect.Method; public class $Proxy0 extends com.learn.proxyimp.interfaces.ProxyWithMe implements org.proxydemo.interfaces.HelloWorld { public $Proxy0(com.learn.proxyimp.interfaces.InvocationHandlerByMe h){ this.h=h; } public void say(java.lang.String args0){ try{ Class> temp=Class.forName("org.proxydemo.interfaces.HelloWorld"); Method method=temp.getMethod("say",new Class[] {java.lang.String.class}); h.invoke(this,method,new Object[] {args0}); } catch (Throwable e) {e.printStackTrace();}} }