Java动态编译实例源码

Linux大全评论843 views阅读模式

思路:

1、创建Java代码的字符串

2、将代码字符串通过IO流以文件形式存放到硬盘

3、将生产的文件进行编译成class

4、通过反射调用该class

注意:

生成的class文件要在上述代码能够调用到的位置

源码:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class TestCompiler {

    private final static String className = "Compiler";
    private final static String classLocation = System.getProperty("user.dir") + "\\bin";
    private final static String fileName = classLocation + "\\" + className + ".java";
    private static StringBuffer javaCode = null;
   
    static {
       
        String br = "\r\n";
        javaCode = new StringBuffer();
        javaCode.append("public class " + className + "{" + br
                + "\tpublic static void main(String[] args) {" + br
                + "\t\tSystem.out.println(\"Hello World!\");" + br + "\t}"
                + br + "}");
    }

    private static void getJavaCode(StringBuffer buffer) {

        if (buffer != null && !buffer.toString().equals("")) {
            javaCode = buffer;
        }
    }

    private static void createFileCode() {

        File file = new File(classLocation);

        if (!file.exists()) {
            file.mkdir();
        }

        try {
            FileWriter writer = new FileWriter(new File(fileName));
            writer.write(javaCode.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void compilerJavaCode() {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(
                null, null, null);
        Iterable<? extends JavaFileObject> sourcefiles = fileManager.getJavaFileObjects(fileName);
        Iterable<String> options = Arrays.asList("-d", classLocation);
        compiler.getTask(null, fileManager, null, options, null, sourcefiles)
                .call();
        try {
            fileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void execute() {
        URL[] urls;
        try {
            urls = new URL[] { new URL("file:" + classLocation) };
            URLClassLoader loader = new URLClassLoader(urls);
            Class<?> c = loader.loadClass(className);
            c.getMethod("main", String[].class).invoke(null,
                    (Object) new String[] { "" });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

企鹅博客
  • 本文由 发表于 2020年7月29日 15:58:44
  • 转载请务必保留本文链接:https://www.qieseo.com/136196.html

发表评论