JVM自定義類加載器加載指定classPath下的全部class及jar

1、JVM中的類加載器類型

  從Java虛擬機的角度講,只有兩種不一樣的類加載器:啓動類加載器和其餘類加載器。
  1.啓動類加載器(Boostrap ClassLoader):這個是由c++實現的,主要負責JAVA_HOME/lib目錄下的核心 api 或 -Xbootclasspath 選項指定的jar包裝入工做。
  2.其餘類加載器:由java實現,能夠在方法區找到其Class對象。這裏又細分爲幾個加載器
    a).擴展類加載器(Extension ClassLoader):負責用於加載JAVA_HOME/lib/ext目錄中的,或者被-Djava.ext.dirs系統變量指定所指定的路徑中全部類庫(jar),開發者能夠直接使用擴展類加載器。java.ext.dirs系統變量所指定的路徑的能夠經過System.getProperty("java.ext.dirs")來查看。
    b).應用程序類加載器(Application ClassLoader):負責java -classpath或-Djava.class.path所指的目錄下的類與jar包裝入工做。開發者能夠直接使用這個類加載器。在沒有指定自定義類加載器的狀況下,這就是程序的默認加載器。
    c).自定義類加載器(User ClassLoader):在程序運行期間, 經過java.lang.ClassLoader的子類動態加載class文件, 體現java動態實時類裝入特性。html


  這四個類加載器的層級關係,以下圖所示。java

      

 

2、爲何要自定義類加載器

  1. 區分同名的類:假定在tomcat 應用服務器,上面部署着許多獨立的應用,同時他們擁有許多同名卻不一樣版本的類。要區分不一樣版本的類固然是須要每一個應用都擁有本身獨立的類加載器了,不然沒法區分使用的具體是哪個。
  2. 類庫共享:每一個web應用在tomcat中均可以使用本身版本的jar。但存在如Servlet-api.jar,java原生的包和自定義添加的Java類庫能夠相互共享。
  3. 增強類:類加載器能夠在 loadClass 時對 class 進行重寫和覆蓋,在此期間就能夠對類進行功能性的加強。好比使用javassist對class進行功能添加和修改,或者添加面向切面編程時用到的動態代理,以及 debug 等原理。
  4. 熱替換:在應用正在運行的時候升級軟件,不須要從新啓動應用。好比toccat服務器中JSP更新替換。

 

3、自定義類加載器

  3.1 ClassLoader實現自定義類加載器相關方法說明

    要實現自定義類加載器須要先繼承ClassLoader,ClassLoader類是一個抽象類,負責加載classes的對象。自定義ClassLoader中至少須要瞭解其中的三個的方法: loadClass,findClass,defineClass。
   c++

public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
throws ClassFormatError
{
return defineClass(name, b, off, len, null);
}

    loadClass:JVM在加載類的時候,都是經過ClassLoader的loadClass()方法來加載class的,loadClass使用雙親委派模式。若是要改變雙親委派模式,能夠修改loadClass來改變class的加載方式。雙親委派模式這裏就不贅述了。
    findClass:ClassLoader經過findClass()方法來加載類。自定義類加載器實現這個方法來加載須要的類,好比指定路徑下的文件,字節流等。
    definedClass:definedClass在findClass中使用,經過調用傳進去一個Class文件的字節數組,就能夠方法區生成一個Class對象,也就是findClass實現了類加載的功能了。git

    貼上一段ClassLoader中loadClass源碼,見見真面目...
      github

protected Class<?> loadClass(String name, boolean resolve)
    throws ClassNotFoundException
{
    synchronized (getClassLoadingLock(name)) {
        // First, check if the class has already been loaded
        Class<?> c = findLoadedClass(name);
        if (c == null) {
            long t0 = System.nanoTime();
            try {
                if (parent != null) {
                    c = parent.loadClass(name, false);
                } else {
                    c = findBootstrapClassOrNull(name);
                }
            } catch (ClassNotFoundException e) {
                // ClassNotFoundException thrown if class not found
                // from the non-null parent class loader
            }

            if (c == null) {
                // If still not found, then invoke findClass in order
                // to find the class.
                long t1 = System.nanoTime();
                c = findClass(name);

                // this is the defining class loader; record the stats
                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                sun.misc.PerfCounter.getFindClasses().increment();
            }
        }
        if (resolve) {
            resolveClass(c);
        }
        return c;
    }
}

    源碼說明...web

/**
* Loads the class with the specified <a href="#name">binary name</a>. The
* default implementation of this method searches for classes in the
* following order:
*
* <ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
* on the parent class loader. If the parent is <tt>null</tt> the class
* loader built-in to the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p> If the class was found using the above steps, and the
* <tt>resolve</tt> flag is true, this method will then invoke the {@link
* #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
*
* <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
* #findClass(String)}, rather than this method. </p>
*
* <p> Unless overridden, this method synchronizes on the result of
* {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
* during the entire class loading process.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @param resolve
* If <tt>true</tt> then resolve the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*/

   翻譯過來大概是:使用指定的二進制名稱來加載類,這個方法的默認實現按照如下順序查找類: 調用findLoadedClass(String)方法檢查這個類是否被加載過 使用父加載器調用loadClass(String)方法,若是父加載器爲Null,類加載器裝載虛擬機內置的加載器調用findClass(String)方法裝載類, 若是,按照以上的步驟成功的找到對應的類,而且該方法接收的resolve參數的值爲true,那麼就調用resolveClass(Class)方法來處理類。 ClassLoader的子類最好覆蓋findClass(String)而不是這個方法。 除非被重寫,這個方法默認在整個裝載過程當中都是同步的(線程安全的)。編程

   resolveClass:Class載入必須連接(link),連接指的是把單一的Class加入到有繼承關係的類樹中。這個方法給Classloader用來連接一個類,若是這個類已經被連接過了,那麼這個方法只作一個簡單的返回。不然,這個類將被按照 Java™規範中的Execution描述進行連接。segmentfault

 3.2 自定義類加載器實現

    按照3.1的說明,繼承ClassLoader後重寫了findClass方法加載指定路徑上的class。先貼上自定義類加載器。api

package com.chenerzhu.learning.classloader;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author chenerzhu
 * @create 2018-10-04 10:47
 **/
public class MyClassLoader extends ClassLoader {
    private String path;

    public MyClassLoader(String path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] result = getClass(name);
            if (result == null) {
                throw new ClassNotFoundException();
            } else {
                return defineClass(name, result, 0, result.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] getClass(String name) {
        try {
            return Files.readAllBytes(Paths.get(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

    

    以上就是自定義的類加載器了,實現的功能是加載指定路徑的class。再看看如何使用。 數組

package com.chenerzhu.learning.classloader;

import org.junit.Test;

/**
 * Created by chenerzhu on 2018/10/4.
 */
public class MyClassLoaderTest {
    @Test
    public void testClassLoader() throws Exception {
        MyClassLoader myClassLoader = new MyClassLoader("src/test/resources/bean/Hello.class");
        Class clazz = myClassLoader.loadClass("com.chenerzhu.learning.classloader.bean.Hello");
        Object obj = clazz.newInstance();
        System.out.println(obj);
        System.out.println(obj.getClass().getClassLoader());
    }
}

    首先經過構造方法建立MyClassLoader對象myClassLoader,指定加載src/test/resources/bean/Hello.class路徑的Hello.class(固然這裏只是個例子,直接指定一個class的路徑了)。而後經過myClassLoader方法loadClass加載Hello的Class對象,最後實例化對象。如下是輸出結果,看得出來實例化成功了,而且類加載器使用的是MyClassLoader。

com.chenerzhu.learning.classloader.bean.Hello@2b2948e2
com.chenerzhu.learning.classloader.MyClassLoader@335eadca

 

4、類Class卸載

  JVM中class和Meta信息存放在PermGen space區域(JDK1.8以後存放在MateSpace中)。若是加載的class文件不少,那麼可能致使元數據空間溢出。引發java.lang.OutOfMemory異常。對於有些Class咱們可能只須要使用一次,就再也不須要了,也可能咱們修改了class文件,咱們須要從新加載 newclass,那麼oldclass就再也不須要了。因此須要在JVM中卸載(unload)類Class。
  JVM中的Class只有知足如下三個條件,才能被GC回收,也就是該Class被卸載(unload):

  1. 該類全部的實例都已經被GC。
  2. 該類的java.lang.Class對象沒有在任何地方被引用。
  3. 加載該類的ClassLoader實例已經被GC。

  很容易理解,就是要被卸載的類的ClassLoader實例已經被GC而且自己不存在任何相關的引用就能夠被卸載了,也就是JVM清除了類在方法區內的二進制數據。
  JVM自帶的類加載器所加載的類,在虛擬機的生命週期中,會始終引用這些類加載器,而這些類加載器則會始終引用它們所加載的類的Class對象。所以這些Class對象始終是可觸及的,不會被卸載。而用戶自定義的類加載器加載的類是能夠被卸載的。雖然知足以上三個條件Class能夠被卸載,可是GC的時機咱們是不可控的,那麼一樣的咱們對於Class的卸載也是不可控的。

 

5、JVM自定義類加載器加載指定classPath下的全部class及jar

  通過以上幾個點的說明,如今能夠實現JVM自定義類加載器加載指定classPath下的全部class及jar了。這裏沒有限制class和jar的位置,只要是classPath路徑下的都會被加載進JVM,而一些web應用服務器加載是有限定的,好比tomcat加載的是每一個應用classPath+「/classes」加載class,classPath+「/lib」加載jar。如下就是代碼啦...

  

package com.chenerzhu.learning.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author chenerzhu
 * @create 2018-10-04 12:24
 **/
public class ClassPathClassLoader extends ClassLoader{

    private static Map<String, byte[]> classMap = new ConcurrentHashMap<>();
    private String classPath;

    public ClassPathClassLoader() {
    }

    public ClassPathClassLoader(String classPath) {
        if (classPath.endsWith(File.separator)) {
            this.classPath = classPath;
        } else {
            this.classPath = classPath + File.separator;
        }
        preReadClassFile();
        preReadJarFile();
    }

    public static boolean addClass(String className, byte[] byteCode) {
        if (!classMap.containsKey(className)) {
            classMap.put(className, byteCode);
            return true;
        }
        return false;
    }

    /**
     * 這裏僅僅卸載了myclassLoader的classMap中的class,虛擬機中的
     * Class的卸載是不可控的
     * 自定義類的卸載須要MyClassLoader不存在引用等條件
     * @param className
     * @return
     */
    public static boolean unloadClass(String className) {
        if (classMap.containsKey(className)) {
            classMap.remove(className);
            return true;
        }
        return false;
    }

    /**
     * 遵照雙親委託規則
     */
    @Override
    protected Class<?> findClass(String name) {
        try {
            byte[] result = getClass(name);
            if (result == null) {
                throw new ClassNotFoundException();
            } else {
                return defineClass(name, result, 0, result.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] getClass(String className) {
        if (classMap.containsKey(className)) {
            return classMap.get(className);
        } else {
            return null;
        }
    }

    private void preReadClassFile() {
        File[] files = new File(classPath).listFiles();
        if (files != null) {
            for (File file : files) {
                scanClassFile(file);
            }
        }
    }

    private void scanClassFile(File file) {
        if (file.exists()) {
            if (file.isFile() && file.getName().endsWith(".class")) {
                try {
                    byte[] byteCode = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
                    String className = file.getAbsolutePath().replace(classPath, "")
                            .replace(File.separator, ".")
                            .replace(".class", "");
                    addClass(className, byteCode);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    scanClassFile(f);
                }
            }
        }
    }

    private void preReadJarFile() {
        File[] files = new File(classPath).listFiles();
        if (files != null) {
            for (File file : files) {
                scanJarFile(file);
            }
        }
    }

    private void readJAR(JarFile jar) throws IOException {
        Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            JarEntry je = en.nextElement();
            je.getName();
            String name = je.getName();
            if (name.endsWith(".class")) {
                //String className = name.replace(File.separator, ".").replace(".class", "");
                String className = name.replace("\\", ".")
                        .replace("/", ".")
                        .replace(".class", "");
                InputStream input = null;
                ByteArrayOutputStream baos = null;
                try {
                    input = jar.getInputStream(je);
                    baos = new ByteArrayOutputStream();
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];
                    int bytesNumRead = 0;
                    while ((bytesNumRead = input.read(buffer)) != -1) {
                        baos.write(buffer, 0, bytesNumRead);
                    }
                    addClass(className, baos.toByteArray());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (baos != null) {
                        baos.close();
                    }
                    if (input != null) {
                        input.close();
                    }
                }
            }
        }
    }

    private void scanJarFile(File file) {
        if (file.exists()) {
            if (file.isFile() && file.getName().endsWith(".jar")) {
                try {
                    readJAR(new JarFile(file));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    scanJarFile(f);
                }
            }
        }
    }


    public void addJar(String jarPath) throws IOException {
        File file = new File(jarPath);
        if (file.exists()) {
            JarFile jar = new JarFile(file);
            readJAR(jar);
        }
    }
}

  

  如何使用的代碼就不貼了,和3.2節自定義類加載器的使用方式同樣。只是構造方法的參數變成classPath了,篇末有代碼。當建立MyClassLoader對象時,會自動添加指定classPath下面的全部class和jar裏面的class到classMap中,classMap維護className和classCode字節碼的關係,只是個緩衝做用,避免每次都從文件中讀取。自定義類加載器每次loadClass都會首先在JVM中找是否已經加載className的類,若是不存在就會到classMap中取,若是取不到就是加載錯誤了。

 

6、最後

  至此,JVM自定義類加載器加載指定classPath下的全部class及jar已經完成了。這篇博文花了兩天才寫完,在寫的過程當中有意識地去了解了許多代碼的細節,收穫也不少。原本最近僅僅是想實現Quartz控制檯頁面任務添加支持動態class,結果不知不覺跑到類加載器的坑了,在此也趁這個機會總結一遍。固然以上內容並不能保證正確,因此但願你們看到錯誤可以指出,幫助我更正已有的認知,共同進步。。。

 

本文的代碼已經上傳github:https://github.com/chenerzhu/learning/tree/master/classloader  歡迎下載和指正。

SpringBoot實現可視化動態操做Quartz定時任務:https://github.com/chenerzhu/quartz-console

參考文章:

  深度分析Java的ClassLoader機制(源碼級別)

  自定義類加載器-從.class和.jar中讀取

  Class熱替換與卸載

相關文章
相關標籤/搜索