java1.6 动态编译代码的例子

package demo;

import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaFileObject.Kind;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;

public class CompileString {
    public static void main(String[] args) throws Exception {
        //通过系统工具提供者获得动态编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //获得一个文件管理器,它的功能主要是提供所有文件操作的规则,
       //如源代码路径、编译的classpath,class文件目标目录等,其相关属性都提供默认值
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        StringObject so = new StringObject("demo.CalculatorTest", "package demo;" +
                "  class CalculatorTest {" +
                "	public int multiply(int multiplicand, int multiplier) {" +
                "		System.out.println(multiplicand);" +
                "		System.out.println(multiplier);" +
                "		return multiplicand * multiplier;" +
                "	}" +
                "}");

        JavaFileObject file = so;
        // 指定 javac 的命令行参数
        // 注意:最好将编译后的.class文件放到当前JVM实例的类路径上,否则加载不鸟
        Iterable options = Arrays.asList("-d", "E:\\workspace\\hellosbt\\target\\scala-2.9.1\\classes");
        // 指定有哪些源文件需要被编译
        Iterable<? extends JavaFileObject> files = Arrays.asList(file);
        
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, files);

        Boolean result = task.call();
       
        if (result) {
            System.out.println("编译成功");
            Class<?> clazz = Class.forName("demo.CalculatorTest");

            Object instance = clazz.newInstance();

            Method m = clazz.getMethod("multiply", new Class[]{int.class, int.class});

            Object[] o = new Object[]{1, 2};
            m.invoke(instance, o);
        }
    }
}

class StringObject extends SimpleJavaFileObject {
    private String contents = null;

    public StringObject(String className, String contents) throws Exception {
        super(new URI(className), Kind.SOURCE);
        this.contents = contents;
    }

    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        return contents;
    }
}

你可能感兴趣的:(java1.6 动态编译代码的例子)