類比JDK動態代理(JAVA設計模式)

來源:互聯網
上載者:User

JDK6提供了Javacompiler,StandardJavaFileManager,Iterable實現對.java檔案編譯的方法。

架構在實現代理的時候可以使用CGLIB直接產生2進位檔案,不需要產生.java檔案。

//介面public interface Moveable {void move();void stop();}

//實現Moveable介面public class Tank implements Moveable{public void move() {System.out.println("tank move()...");}public void stop() {System.out.println("tank stop()...");}}

import java.lang.reflect.Method;//除moveable之外再建立一個介面InvocationHandlerpublic interface InvocationHandler {void invoke(Object o,Method m);}

import java.lang.reflect.Method;//實現InvocationHandler介面,自訂需要添加的內容,建立添加日誌的Handlerpublic class LogHandler implements InvocationHandler{Object target;public LogHandler(Object target) {this.target = target;}public void invoke(Object o, Method m) {System.out.println("logHandler start...");try {m.invoke(target);} catch (Exception e) {e.printStackTrace();}System.out.println("logHandler end...");}}

import java.io.File;import java.io.FileWriter;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import javax.tools.JavaCompiler;import javax.tools.StandardJavaFileManager;import javax.tools.ToolProvider;//類比JDK的代理類Proxypublic class Proxy {//類比JDK建立代理類的方法,JDK中還有一個ClassLoader參數,這裡傳入介面和需要添加的邏輯Handler,結果返回一個代理的對象。public static Object newProxyInstance(Class inf,InvocationHandler h) throws Exception{String methodStr = "";String rt = "\r\n";Method[] methods = inf.getMethods();for(Method m : methods){methodStr += "@Override" + rt +  "public void " + m.getName() + "() {" + rt + "    try {" + rt + "    Method md = " + inf.getName() + ".class.getMethod(\"" + m.getName() + "\");" + rt + "    h.invoke(this, md);" + rt + "    }catch(Exception e) {e.printStackTrace();}" + rt + "}";}//組建代理程式對象的類String src = "package proxy;" +  rt +"import java.lang.reflect.Method;" + rt +"public class $Proxy1 implements " + inf.getName() + "{" + rt +"    proxy.InvocationHandler h;" + rt +"    public $Proxy1(InvocationHandler h) {" + rt +"        this.h = h;" + rt +"    }" + rt +methodStr +"}";String fileName = "D:/share/test/proxy/$Proxy1.java";File f = new File(fileName);FileWriter fw = new FileWriter(f);fw.write(src);//產生.java檔案fw.flush();fw.close();//對類進行編譯JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);Iterable units =  fileManager.getJavaFileObjects(fileName);compiler.getTask(null, fileManager, null, null, null, units).call();//編譯,產生.class檔案。fileManager.close();URL[] url  = new URL[]{new URL("file:/D:/share/test/")};URLClassLoader loader = new URLClassLoader(url);Constructor c = loader.loadClass("proxy.$Proxy1").getConstructor(InvocationHandler.class);//構造器有參數return c.newInstance(h);//載入.class檔案,產生對象。}}
public class Client {public static void main(String[] args) throws Exception {InvocationHandler h = new LogHandler(new Tank());//告訴代理類,我需要添加什麼邏輯。Moveable m = (Moveable) Proxy.newProxyInstance(Moveable.class, h);//返回代理的對象。m.move();//實際這裡是調用添加過邏輯的代理類的方法。m.stop();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.