java----动态编译
java执行外部程序的方式
1 Runtime
2 Process Builder
动态编译的两种做法:
-通过Runtime调用javac,启动新的进程去操作
Runtime run =Runtime.getRuntime(); Process process=run.exec("javac -cp d:/myjava/ HelloWorld.java");
-通过JavaCompiler动态编译
public static void main(String[] args) throws IOException { //将本地文件进行编译 JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); int run = systemJavaCompiler.run(null, null, null, "C:\\Users\\zhengyan\\Desktop\\Test\\src\\main\\java\\com\\zy\\Test.java"); System.out.println(run); //将一个字符串进行编译(使用IO流) String str = "public class T{\n" + "\tpublic void test(){}\n" + "}"; File file = new File("T.java"); if (!file.exists()){ file.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream("T.java"); fileOutputStream.write(str.getBytes()); } run = systemJavaCompiler.run(null, null, null, "T.java"); System.out.println(run); }
补充
public class T{ public static void main(String[] args) { System.out.println("hellow"); } }
动态运行编译好的类的两种做法:
-通过Runtime.getRuntime/运行启动新的进程运行
public static void main(String[] args) throws IOException { Runtime run =Runtime.getRuntime(); Process process=run.exec("java -cp / T"); //可能用"/"不好使,我们把T.class复制到桌面 //Process process=run.exec("java -cp C:\\Users\\zhengyan\\Desktop T"); //可能用"/"不好使,我们把T.class复制到桌面 //因为T程序需要输出内容,所以我们打印出来 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String info; while ((info=bufferedReader.readLine())!=null){ System.out.println(info); } System.out.println("end"); }
通过反射运行编译好的类
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { URL[] urls = new URL[] {new URL("file:/C:/Users/zhengyan/Desktop/")}; URLClassLoader urlClassLoader = new URLClassLoader(urls); Class<?> t = urlClassLoader.loadClass("T"); //反射 Method main = t.getMethod("main",String[].class); //静态方法不需要实例化 T 对象 //main.invoke(Object object,Object... args); main.invoke(null,(Object)new String[]{"a","b"}); //main.invoke(null,new String[]{"a","b"}); //如果不强转Object,编译器会变成成main.invoke(null,"a","b"}); }