java中的動態載入和熱替換

來源:互聯網
上載者:User

1.C++編寫的程式需要經過編譯稱為目標檔案,然後在程式執行之前進行連結後才可以稱為可以啟動並執行可執行程式,這個連結可以發生在程式運行之前,也可以發生在程式運行後(在核心中完成連結過程)再被執行。(運行可以理解為雙擊開啟)。而Java則只需要編譯成位元組碼,然後交給JVM解析器去連結執行就可以了。(C++系列也擁有動態載入和動態連結等概念)


2.Java的動態載入實際上就是程式在執行過程中可以根據程式設定去載入需要被執行的位元組碼檔案。


3.熱替換屬於動態載入的一種,但是熱替換是特殊的動態載入機制。


4.動態載入在Java中有2種實現,第一種通過ClassLoader.loadClass()去載入,ClassLoader最進階別的類載入器,所有的類都歸他管理,用loadClass載入的類,是未經過初始化的,所以很多靜態變數和方法無法被使用,第二種方法則是,Class.forName().用這個方法載入的類已經經過初始化。


5.而如何?熱替換呢。首先我們要知道ClassLoader中的loadClass在載入類的時候會檢測該類是否已經存在,如果存在則不會去載入,如果不存在則載入該類並緩衝。所以預設的ClassLoader是無法實現熱替換的。換句話說,要實現熱替換就必須實現一個自己的MyClassLoader,實現一個自己的用於載入類的方法findClass(),在方法裡面要做的事情就是讀取本地位元組碼檔案,只用父類的defineClass()方法去解析它。這樣就可以擷取新的類了,而舊的類由於ClassLoader不可達,所以會被GC回收。


下面是MyClassLoader的代碼:

import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class MyClassLoader extends ClassLoader {    public MyClassLoader() {    }    public Class<?> findClass(String name) throws ClassNotFoundException {        String classPath = MyClassLoader.class.getResource("/").getPath();        String fileName = name.replace(".", "/") + ".class";        File classFile = new File(classPath, fileName);        if(!classFile.exists()) {            throw new ClassNotFoundException(classFile.getPath() + " 不存在");        } else {            ByteArrayOutputStream bos = new ByteArrayOutputStream();            ByteBuffer bf = ByteBuffer.allocate(1024);            FileInputStream fis = null;            FileChannel fc = null;            try {                fis = new FileInputStream(classFile);                fc = fis.getChannel();                while(fc.read(bf) > 0) {                    bf.flip();                    bos.write(bf.array(), 0, bf.limit());                    bf.clear();                }            } catch (FileNotFoundException var20) {                var20.printStackTrace();            } catch (IOException var21) {                var21.printStackTrace();            } finally {                try {                    fis.close();                    fc.close();                } catch (IOException var19) {                    var19.printStackTrace();                }            }            return this.defineClass(bos.toByteArray(), 0, bos.toByteArray().length);        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.