java 動態編譯
阿新 • • 發佈:2018-03-02
runtime {} runt mpi src lan provider null roc
1.第一種方式:JavaCompiler+Runntime
public static void run() { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int res = compiler.run(null,null,null,"G:/github/src/com/reflect/Abc.java"); System.err.println(res == 0?"成功":"失敗"); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("java -cp G:/github/src/com/reflect/"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String temp; while ((temp = reader.readLine())!= null){ System.err.println(temp); } } catch (IOException e) { e.printStackTrace(); } }
2.第二種方式:URLClassLoader+反射
public static void run2() throws Exception { URL[] urls = new URL[]{new URL("file:/"+"G:/github/src/com/reflect/"),new URL("file:/"+"G:/github/src/com/net/v1/")}; System.err.println(Arrays.toString(urls)); URLClassLoader loader = new URLClassLoader(urls); Class<?> abc = loader.loadClass("com.reflect.Abc"); Method main = abc.getMethod("main", String[].class); main.invoke(null,(Object) new String[]{}); }
java 動態編譯