Java 动态代理机制分析及扩展,第 2 部分
2010-02-24 00:00:00 来源:WEB开发网清单 4. ProxyEx 的静态方法 getMethodEntity()
private static String getMethodEntity( Method method )
{
String template = "\n{"
+ "\n java.lang.reflect.Method method = null;"
+ "\n try{"
+ "\n method = &Class.getMethod( \"&MethodName\", &ParameterTypes );"
+ "\n }"
+ "\n catch(Exception e){"
+ "\n }"
+ "\n Object r = null;"
+ "\n try{"
+ "\n r = handler.invoke( this, method, &ParameterValues );"
+ "\n }&Exceptions"
+ "\n &Return"
+ "\n}";
String result = template.replaceAll("&MethodName", method.getName() )
.replaceAll("&Class", method.getDeclaringClass().getName() + ".class")
.replaceAll("&ParameterTypes", getMethodParameterTypesHelper(method))
.replaceAll("&ParameterValues", getMethodParameterValuesHelper(method) )
.replaceAll("&Exceptions", getMethodParameterThrowablesHelper(method))
.replaceAll("&Return", getMethodReturnHelper( method ) );
return result;
}
当为 Class 类型对象生成该类型对应的字符代码时,可能涉及数组类型,反推过程会需要按递归方法生成代码,这部分工作由 getTypeHelper 方法提供
更多精彩
赞助商链接