1/04/2012

沉默ClassLoader

JVM環境中沉默英雄ClassLoader,無聲無息將Java Class載入至JVM讓程式能夠於JVM運行。

瞭解ClassLoader定義

The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.[1] Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of class loaders. Delegation is an important concept to understand when learning about class loaders.

為什麼需要瞭解它

雖然在大部份時間我們並不需要去瞭解它,甚至不會感覺它的存在,但總是有一些特別的需求需要自行客制化ClassLoader。

  • 單純想瞭解它的運作
  • 程式可能存在網路某個地方與不同存取協定
  • 能夠在運作時重新載入程式(jar, class) JRebel
  • 安全性考量用來載入特殊格式(加密格式)
  • 御載(unload)程式在某些極端因素考量下
  • 客制化

運作

JVM主要有三層ClassLoader,每一層負責載入程式都不相同。

ClassLoader Hiearchy

  1. Bootstrap ClassLoader (also called the primordal class loader)

    Java ClassLoader最上層(root), 本身不是Java程式而是C++程式撰寫而成,主要用來載入$JAVA_HOME/jre/lib/rt.jar

  2. Extensions ClassLoader

    Bootstrap子類別用來載入系統路徑$JAVA_HOME/jre/lib/ext/*.jar

  3. System ClassLoader

    Extensions子類別用來載入使用者定義[-cp, -classpath, $CLASSPATH]變數的程式

  4. User defined ClassLoader

    容許使用者自行定義要如何將Class載入

載入過程

Linking

  1. Loading Step

    載入bytecode,此階段類別尚未能夠使用Class物件 。

  2. Linking Step

    Verify階段ClassLoader判斷載入byte code是否正確與否。preparation階段用來準備類別內所定義資料結構[fields, methods, implemented interfaces]。Resolving階段用來載入所有類別內所參考類別(referenced class)[Superclasses, Interface, Fields, Method signature, Local variables],當然只能看Code才能知道如何實作。

  3. Initialization Step

    用來初始化Class variables同時定義static程式將被執行

ClassLoader常見問題

  • ClassNotFoundException

    很明顯告訴你ClassLoader無法找到指定Class所在位置,使用Class名稱去尋找,可使用此參數–verbose:class找錯誤。

  • NoClassDefFoundError

    尋找定義於被載入中的類別所使用到參考類別。因而丟出的執行時期例外,這個錯誤通常是因為 classpath 的設定錯誤而丟出的。

  • ClassCastException

    ClassLoader無法轉型錯誤,已存在相同Class在VM當中或者與定義的類別有差異

雖然是很粗略介紹ClassLoader運作尚有一些東西還要精進。

No comments:

Post a Comment