代理模式——動態代理(自己寫一個)


思路

難點:proxy類,它的作用就是幫我們產生代理類。


  1. 將所有方法代碼拼接成字符串
  2. 將生成代理類的代碼拼接成字符串(包含所有方法拼接成的字符串)
  3. 將此字符串寫入文件中、並使用JavaComplier對它進行編譯
  4. 將編譯好的文件load進內存供我們使用,並返回代理實例。

Proxy代碼:

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;  
    }  
}  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章