[Java] 动态代理---动态生成java文件并编译成class文件 →→→→→进入此内容的聊天室

来自 , 2019-07-14, 写在 Java, 查看 109 次.
URL http://www.code666.cn/view/193002e6
  1. package com.cjb.proxy;
  2.  
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.lang.reflect.Constructor;
  6. import java.net.URL;
  7. import java.net.URLClassLoader;
  8.  
  9. import javax.tools.JavaCompiler;
  10. import javax.tools.StandardJavaFileManager;
  11. import javax.tools.ToolProvider;
  12. import javax.tools.JavaCompiler.CompilationTask;
  13.  
  14.  
  15. public class Test
  16. {
  17.  public static void main(String[] args) throws Exception
  18.  {
  19.   String rt = "\r\n";
  20.   String source = "package com.cjb.proxy;" + ""+ rt
  21.     + "public class Dealer implements Store"+ rt  + "{"+ rt  + "private Store s;" + rt +
  22.     "public Dealer(Store s)"+ rt  + " {" + "  this.s = s;"+ rt
  23.     + " }" + rt +
  24.  
  25.     " public void sell()" + " {"+ rt
  26.     + "  System.out.println(\"price markup....\");"+ rt
  27.     + "  s.sell();" + " }" + rt+
  28.     "}";
  29.  
  30.   String fileName = System.getProperty("user.dir")//获取到项目的根路径
  31.     + "/src/com/cjb/proxy/Dealer.java";
  32.   File f = new File(fileName);
  33.   FileWriter fw = new FileWriter(f);
  34.   fw.write(source);
  35.   fw.flush();
  36.   fw.close();//这里只是产生一个JAVA文件,简单的IO操作
  37.  
  38.   // compile下面开始编译这个Store.java
  39.   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  40.   StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null,
  41.     null, null);
  42.   Iterable units = fileMgr.getJavaFileObjects(fileName);
  43.   CompilationTask t = compiler.getTask(null, fileMgr, null, null, null,
  44.     units);
  45.   t.call();
  46.   fileMgr.close();
  47.  
  48.   // load into memory and create an instance
  49.   URL[] urls = new URL[] { new URL("file:/"
  50.     + System.getProperty("user.dir") + "/src") };
  51.   URLClassLoader ul = new URLClassLoader(urls);
  52.   Class c = ul.loadClass("com.cjb.proxy.Dealer");
  53.   System.out.println(c);
  54.  
  55. //客户端调用
  56.  
  57.   Constructor ctr = c.getConstructor(Store.class);
  58.   Store s = (Store)ctr.newInstance(new Supermarket());//这里看到,这个我们这个代理类必须实现Store的原因
  59.   s.sell();
  60.  }
  61. }//源代码片段来自云代码http://yuncode.net
  62.                        

回复 "动态代理---动态生成java文件并编译成class文件"

这儿你可以回复上面这条便签

captcha