Java 如何实现动态编译和动态运行

动态编译可以通过两种方式实现:

  1. 通过Runtime调用javac,启动新的进程去操作
	Runtime runtime = Runtime.getRuntime();
		try {
			Process process = runtime
					.exec("javac -cp /User/test/  helloWorld.java");
          
            
		} catch (IOException e) {
			e.printStackTrace();
		}

通过JavaCompile 动态编译 

如果想要详细了解JavaCompiler,请看官网 https://www.ibm.com/developerworks/cn/java/j-lo-jse64/index.html

		 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		int result =  compiler.run(null, null, null, "src/com/begin/utils/annotation/Demo.java");
		
		 System.out.println(result==0?"编译成功":"编译失败");

 

动态运行的两种实现方法:

1. 通过Runtime来实现动态运行

Runtime runtime = Runtime.getRuntime();
		try {
			Process process = runtime
					.exec("java -cp /Users/test/ Demo");
            InputStream inputStream = process.getInputStream();
           	System.out.println("=====");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String info = "";
            while((info=reader.readLine())!=null) {
            	System.out.println(info);
            }
            
		} catch (IOException e) {
			e.printStackTrace();
		}

2. 通过反射动态运行main方法:

URL[] urls = new URL[] {new URL("file:/"+"Users/zhanzhandu/eclipse-workspace/Test/src/com/begin/utils/annotation/")};
		     URLClassLoader classLoader = new URLClassLoader(urls);
		     Class class1 = classLoader.loadClass("Demo");
		     
		     //调用加载类的main方法
		     Method method = class1.getMethod("main" , String[].class);
		     method.invoke(null,(Object)new String[] {"aa","bb"});
		     
		     //由于可变参数式JDK5.0之后才有的,上面的代码会编译成,m.invoke(null, "aa", "bb"),就放生了参数个数不匹配的问题。
		     //因此,必须要加上(Object)转型,避免这个问题。
		 

 

你可能感兴趣的:(Java)