动态生成类小案例,调用JDK自身的编译工具api,比较有用。
- package com.lzz.proxy.compiler;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import javax.tools.JavaCompiler;
- import javax.tools.JavaCompiler.CompilationTask;
- import javax.tools.StandardJavaFileManager;
- import javax.tools.ToolProvider;
- /**
- * 动态生成类以及编译,JDK版本必须要在1.6,或者1.6以上
- * @author Administrator
- *
- */
- public class Compiler {
- //回车加换行符
- static String rt="\r\n";
- //生成类的源文件,写成字符串的形式
- static String src=
- "package com.lzz.proxy;"+rt+
- "public class TankLogProxy implements Moveable {"+rt+
- " Moveable t;"+rt+
- " public TankLogProxy(Moveable t) {"+rt+
- " this.t=t;"+rt+
- " }"+rt+
- "@Override"+rt+
- " public void move() {"+rt+
- " System.out.println(\"log: start move....... \");"+rt+
- " t.move();"+rt+
- " System.out.println(\"log: end move......\");"+rt+
- " }"+rt+
- "}";
- public static void main(String[] args) throws Exception {
- //写文件,目录可以自己定义
- String filename=System.getProperty("user.dir")+"/src/com/lzz/proxy/TankLogProxy.java";
- System.out.println(filename);
- File file =new File(filename);
- FileWriter fw=new FileWriter(file);
- fw.write(src);
- fw.flush();
- fw.close();
- //编译文件,调用jdk本身的工具
- JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
- System.out.println(compiler.getClass().getName());
- /* compiler.getStandardFileManager(null, null, null);三个参数
- 第一个 用来监听编译异常错误等
- 第二个,第三个 用来设置语言和编码,这里使用默认就行了*/
- StandardJavaFileManager sjfm=compiler.getStandardFileManager(null, null, null);
- Iterable units=sjfm.getJavaFileObjects(filename);
- CompilationTask ct=compiler.getTask(null, sjfm, null, null, null, units);
- ct.call();
- sjfm.close();
- }
- }