思路
难点:proxy类,它的作用就是帮我们产生代理类。
- 将所有方法代码拼接成字符串。
- 将生成代理类的代码拼接成字符串(包含所有方法拼接成的字符串)。
- 将此字符串写入文件中、并使用JavaComplier对它进行编译。
- 将编译好的文件load进内存供我们使用,并返回代理实例。
public class Proxy {
public static Object newProxyInstance(Class intefc, InvocationHandler handle) throws Exception {
String rt = "\r\t" ;
String methodStr = "" ;
// first we should realize all the methods of the interface
Method[] methods = intefc.getMethods();
for (Method m : methods) {
methodStr +="public void "+m.getName()+"(){"+rt+
" try{"+rt+
" Method method = "+intefc.getName()+".class.getMethod(\""+m.getName()+"\");" + rt +
" handle.invoke(this,method);" +rt+
" }catch(Exception ex){}" +rt+
"}" ;
}
String clazzStr = "package com.zdp.dynamicProxy;"+rt+
"import java.lang.reflect.Method;"+rt+
"public class $Proxy1 implements "+intefc.getName()+"{"+rt+
" private com.zdp.dynamicProxy.InvocationHandler handle ;"+rt+
" public $Proxy1(InvocationHandler handle){"+rt+
" this.handle=handle;"+rt+
" }"+rt+
" @Override"+rt+
methodStr +rt+
"}";
// write to a java file
String uri = "D:/develop_environment/babasport/homework/src/com/zdp/dynamicProxy/$Proxy1.java";
File file = new File(uri) ;
FileWriter writer = null ;
try {
writer = new FileWriter(file);
writer.write(clazzStr) ;
writer.flush() ;
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(writer !=null){
writer.close() ;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//load the java file, and then create an instance
String url="D:/develop_environment/babasport/homework/src/";
URL[] urls = new URL[] {new URL("file:/" + url)};
URLClassLoader urlLoader = new URLClassLoader(urls);
Class c = urlLoader.loadClass("com.zdp.dynamicProxy.$Proxy1");
//return the proxy instance
Constructor ctr = c.getConstructor(InvocationHandler.class);
Object proxyInstance = ctr.newInstance(handle);
return proxyInstance;
}
}