设为首页 加入收藏

TOP

动态代理类的实现和解析(二)
2019-09-25 11:18:24 】 浏览:176
Tags:动态 代理 实现 解析
ennerateClass {
10 public static void generate(Class<?> clazz) { 11 String methodStr = ""; //:方法字符串的拼接 12 String classStr = ""; //:类名的拼接 13 String packageStr = ""; //:导入包名的拼接 14 String classParamStr = ""; // 15 String staticCodeStr = "static {\ntry {";//:静态代码块的拼接 16 String member_var = ""; //:成员变量的拼接 17 String package1 = clazz.getPackage().getName(); 18 String simpleName = clazz.getSimpleName(); //:获得简单类名 19 String className = clazz.getName(); //:获得权限定类名 20 //:构造函数的拼接 21 String counstructStr = "public " + simpleName + "$proxy0(InvocationHandler h) {\r\n" + " super(h);\r" 22 + " }\n"; 23 // :导包 24 packageStr = "package " + package1 + ";\n" 25 + "import proxyBase.MyProxy;\r import java.lang.reflect.InvocationHandler;\n" 26 + "import java.lang.reflect.Method;\n"; 27 // :构建类名 28 classStr += "public class " + simpleName + "$proxy0 extends MyProxy implements " + simpleName + "{\n" + ""; 29 // :构建代理类的方法 30 Method[] methods = clazz.getMethods(); 31 int i = 0; 32 for (Method method : methods) { 33 String paramStr = "";//:参数变量拼接 34 int paramCount = 0; //:参数个数计数用来生成参数变量 35 i += 1; 36 member_var += "private static Method m" + i + ";\n";//成员变量的拼接 37 String tempStr = ""; //:参数列表 38 String methodName = method.getName();// 方法名 39 Class<?>[] parameterTypes = method.getParameterTypes();// 参数列表的class类型 40 Class<?> returnType = method.getReturnType();// 返回值类型 41 methodStr += "public final " + returnType.getName() + " " + methodName + "("; 42 // :参数列表名字符串 43 for (Class<?> type : parameterTypes) { 44 paramCount += 1; 45 tempStr += "," + type.getName() + " param" + paramCount; 46 paramStr += ",param" + paramCount; 47 classParamStr += "," + type.getName() + ".class"; 48 } 49 // 50 if (!paramStr.isEmpty()) { 51 paramStr = paramStr.substring(1); 52 } 53 if (!tempStr.isEmpty()) { 54 tempStr = tempStr.substring(1); 55 } 56 if (classParamStr.isEmpty()) { 57 classParamStr = "null"; 58 } else { 59 classParamStr = classParamStr.substring(1); 60 } 61 //:判断返回值是否时void,是则不需要return 62 //方法的拼接 63 if (returnType.getName().equals("void")) { 64 methodStr = methodStr + tempStr + ")\n{\n" + "\ttry{\n\tthis.h.invoke(this,m" + i + ",new Object[]{" 65 + paramStr + "});" + "} catch (Throwable e) {\r\n" + " e.printStackTrace();\r\n" 66 + " }\n}\n"; 67 } else { 68 methodStr = methodStr + tempStr + ")\n{\nObject result=null;\n\ttry{\n\tresult=this.h.invoke(this,m" + i 69 + ",new Object[]{" + paramStr + "});" + "} catch (Throwable e) {\r\n" 70 + " e.printStackTrace();\r\n" + "}\nreturn (" + returnType.getName() + ")result;}\n"; 71 } 72 // :构建静态代码块 73 if (!classParamStr.equals("null")) { 74 staticCodeStr += "m" + i + " = Class.forName(\"" + className + "\").getMethod(\"" + methodName 75 + "\",new Class<?>[]{" + cla
首页 上一页 1 2 3 4 下一页 尾页 2/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇06.Django基础五之django模型层(.. 下一篇通俗易懂设计模式解析——模板方..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目