Java使用代码进行编译与运行

package com.java.basic.compiler;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CompilerTest {

    public static void main(String[] args) throws IOException {

        /**
         * 1. 编译代码
         * 2. 执行代码
         * 3. 线程交互, 获取输入流(执行结果)
         */
        // 代码编译
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        int count = javaCompiler.run(null, null, null,
                "D:/new~dir/project-student/CompilerSource.java");
        System.out.println(count == 0 ? "编译成功": "编译失败");
        // 代码执行
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("java -cp D:/new~dir/project-student/ CompilerSource");
        InputStream in = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String inS = "";
        while ((inS=reader.readLine()) != null) {
            System.out.println(inS);
        }
    }
}

package com.java.basic.compiler;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ReflectTest {

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        /**
         * 1. 加载类进jvm, 获取字节码对象
         * 2. 使用反射调用该方法
         */
        URL[] urls = new URL[]{new URL("file:/D:/new~dir/project-student/")};
        URLClassLoader loader = new URLClassLoader(urls);
        Class c = loader.loadClass("CompilerSource");
        Method m = c.getMethod("main", String[].class);
        m.invoke(null,(Object)new String[]{"a","b"});

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43503284/article/details/85858836