package spring.vhostall.com.proxy; public interface Store { public void sell(); } -------------------------------------------- package spring.vhostall.com.proxy; public class Supermarket implements Store { @Override public void sell() { System.out.println("sel in supermarket....."); } } -------------------------------------------- package spring.vhostall.com.proxy; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import javax.tools.JavaCompiler; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class Test { public static void main(String[] args) throws Exception { String rt = " "; StringBuilder source = new StringBuilder(); source.append("package spring.vhostall.com.proxy;" + rt + rt); source.append("public class Dealer implements Store" + " {" + rt); source.append(" private Store s;" + rt + rt); source.append(" public Dealer(Store s) {" + rt); source.append(" this.s = s;" + rt); source.append(" }" + rt + rt); source.append(" public void sell()" + " {" + rt); source.append(" System.out.println("price markup....");" + rt); source.append(" s.sell();" + rt); source.append(" }" + rt); source.append("}"); String fileName = System.getProperty("user.dir")// 获取到项目的根路径 + "/src/spring/vhostall/com/proxy/Dealer.java"; File f = new File(fileName); FileWriter fw = new FileWriter(f); fw.write(source.toString()); fw.flush(); fw.close();// 这里只是产生一个JAVA文件,简单的IO操作 // compile下面开始编译这个Store.java JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); URL[] urls = new URL[] { new URL("file:/" + System.getProperty("user.dir") + "/src") }; URLClassLoader ul = new URLClassLoader(urls); Class c = ul.loadClass("spring.vhostall.com.proxy.Dealer"); // 客户端调用 Constructor ctr = c.getConstructor(Store.class); Store s = (Store) ctr.newInstance(new Supermarket());// 这里看到,这个我们这个代理类必须实现Store的原因 s.sell(); } }