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