Javaが動的コンパイルと動的実行を実現する方法

1973 ワード

動的コンパイルは、次の2つの方法で実行できます.
  • 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?"    ":"    ");

     
    動的に実行する2つの実装方法:
    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)  ,      。