Java動態編譯

來源:互聯網
上載者:User

標籤:開發人員   執行   cts   too   new   func   cti   sys   obj   

概述:

Java的動態編譯就是在運行期直接編譯.java檔案,執行.class,並且能夠獲得相關的輸入輸出,甚至還能監聽相關的事件。

步驟:

1、建立或自動產生.java檔案

2、調用JavaCompiler擷取編譯器,該類允許開發人員編譯java檔案為class檔案

     JavaCompiler compiler =ToolProvider.getSystemJavaCompiler();

3、擷取檔案管理工具StandardJavaFileManager,用來管理要編譯的.java檔案。getStandardFileManager有3個參數,分別代表監聽器、語言環境、字元集

     StandardJavaFileManager fileManger = compiler.getStandardFileManager(null, null, null);

4、擷取表示給定檔案的檔案對象

   Iterable unils = fileManger.getJavaFileObjects(fileName)

5、擷取編譯任務的future介面CompilationTask,當調用它的call方法時,開始編譯

  CompilationTask t = compiler.getTask(null, fileManger, null, null, null, unils);

  t.call();

6、調用URLClassLoader將編譯的檔案load記憶體,其中需要知道檔案的位置,用URL記錄,其中“file:/”表示本地檔案。

     URL[] urls = new URL[]{new URL("file:/"+System.getProperty("user.dir")+"/scr")};

     URLClassLoader cl = new URLClassLoader(urls);

7、擷取編譯後的類

     Class c = cl.loadClass("com.chensr.util.function.Function");    

8、擷取建構函式,構造方法如果有參數需要配置對應的參數類型

   Constructor constructor = c.getConstructor(String.class);

      Object b =constructor.newInstance("哈哈");

9、執行對應的方法

      Method method=c.getDeclaredMethod("方法名","參數類型"); 

      method.invoke(b,"參數值");

 

具體代碼如下:

 

package com.chensr.util.function;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import javax.tools.JavaCompiler;import javax.tools.JavaCompiler.CompilationTask;import javax.tools.StandardJavaFileManager;import javax.tools.ToolProvider;public class Reflection {    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {        String str ="package com.chensr.util.function; \r\t"+                                        "public class Function { \r\t"+                    "    public Function(String a) { \r\t"+                    "         System.out.println(\"我是建構函式!\"+a);\r\t"+                    "    }\r\t"+                    "    public static void say(){ \r\t"+                    "        System.out.println(\"我由string產生class\");\r\t"+                    "    }\r\t"+                    "}";                //根據str產生.java檔案        String fileName=System.getProperty("user.dir")+
"\\src\\main\\java\\com\\chensr\\util\\function\\Function.java"; System.out.println(fileName); File file = new File(fileName); FileWriter fw = new FileWriter(file); fw.write(str); fw.flush(); fw.close(); //調用JavaCompiler擷取編譯器,該類允許開發人員編譯java檔案為class檔案 JavaCompiler compiler =ToolProvider.getSystemJavaCompiler(); //Java 標準檔案管理工具,第一個參數為監聽器,第二個參數語音環境,第三個參數為字元集 StandardJavaFileManager fileManger = compiler.getStandardFileManager(null, null, null); //擷取表示給定檔案的檔案對象 Iterable unils = fileManger.getJavaFileObjects(fileName); //CompilationTask表示編譯任務的未來的介面。調用call()啟動任務。getTask方法編譯原始碼,並將對應的class檔案產生到指定目錄 CompilationTask t = compiler.getTask(null, fileManger, null, null, null, unils); t.call(); fileManger.close(); //load記憶體,並且建立一個執行個體 URL[] urls = new URL[]{new URL("file:/"+System.getProperty("user.dir")+"/scr")}; URLClassLoader cl = new URLClassLoader(urls); Class c = cl.loadClass("com.chensr.util.function.Function"); //擷取建構函式和執行對應的方法 Constructor constructor = c.getConstructor(String.class); Object b =constructor.newInstance("哈哈"); Method method=c.getDeclaredMethod("say"); method.invoke(b); }}

 

 

 

 

 

 

 

 

 

 

 

 

 

           

 

Java動態編譯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.