[轉載] Java中動態載入jar檔案和class檔案

來源:互聯網
上載者:User

標籤:

轉載自http://blog.csdn.net/mousebaby808/article/details/31788325

概述  諸如tomcat這樣的伺服器,在啟動的時候會載入應用程式中lib目錄下的jar檔案以及classes目錄下的class檔案,另外像spring這類架構,也可以根據指定的路徑掃描並載入指定的類檔案,這個技術可以實現一個容器,容納各類不同的子應用。  Java類由於需要載入和編譯位元組碼,動態載入class檔案較為麻煩,不像C載入動態連結程式庫只要一個檔案名稱就可以搞定,但JDK仍提供了一整套方法來動態載入jar檔案和class檔案。 動態載入jar檔案 [java] view plaincopy 
  1. // 系統類別庫路徑  
  2. File libPath = new File(jar檔案所在路徑);  
  3.   
  4. // 擷取所有的.jar和.zip檔案  
  5. File[] jarFiles = libPath.listFiles(new FilenameFilter() {  
  6.     public boolean accept(File dir, String name) {  
  7.         return name.endsWith(".jar") || name.endsWith(".zip");  
  8.     }  
  9. });  
  10.   
  11. if (jarFiles != null) {  
  12.     // 從URLClassLoader類中擷取類所在檔案夾的方法  
  13.     // 對於jar檔案,可以理解為一個存放class檔案的檔案夾  
  14.     Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);  
  15.     boolean accessible = method.isAccessible();     // 擷取方法的存取權限  
  16.     try {  
  17.         if (accessible == false) {  
  18.             method.setAccessible(true);     // 設定方法的存取權限  
  19.         }  
  20.         // 擷取系統類別載入器  
  21.         URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();  
  22.         for (File file : jarFiles) {  
  23.             URL url = file.toURI().toURL();  
  24.             try {  
  25.                 method.invoke(classLoader, url);    
  26.                 LOG.debug("讀取jar檔案[name={}]", file.getName());  
  27.             } catch (Exception e) {  
  28.                 LOG.error("讀取jar檔案[name={}]失敗", file.getName());  
  29.             }  
  30.         }  
  31.     } finally {  
  32.         method.setAccessible(accessible);  
  33.     }  
  34. }  

動態載入class檔案 [java] view plaincopy 
  1. // 設定class檔案所在根路徑  
  2. // 例如/usr/java/classes下有一個test.App類,則/usr/java/classes即這個類的根路徑,而.class檔案的實際位置是/usr/java/classes/test/App.class  
  3. File clazzPath = new File(class檔案所在根路徑);  
  4.   
  5. // 記錄載入.class檔案的數量  
  6. int clazzCount = 0;  
  7.   
  8. if (clazzPath.exists() && clazzPath.isDirectory()) {  
  9.     // 擷取路徑長度  
  10.     int clazzPathLen = clazzPath.getAbsolutePath().length() + 1;  
  11.   
  12.     Stack<File> stack = new Stack<>();  
  13.     stack.push(clazzPath);  
  14.   
  15.     // 遍曆類路徑  
  16.     while (stack.isEmpty() == false) {  
  17.         File path = stack.pop();  
  18.         File[] classFiles = path.listFiles(new FileFilter() {  
  19.             public boolean accept(File pathname) {  
  20.                 return pathname.isDirectory() || pathname.getName().endsWith(".class");  
  21.             }  
  22.         });  
  23.         for (File subFile : classFiles) {  
  24.             if (subFile.isDirectory()) {  
  25.                 stack.push(subFile);  
  26.             } else {  
  27.                 if (clazzCount++ == 0) {  
  28.                     Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);  
  29.                     boolean accessible = method.isAccessible();  
  30.                     try {  
  31.                         if (accessible == false) {  
  32.                             method.setAccessible(true);  
  33.                         }  
  34.                         // 設定類載入器  
  35.                         URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();  
  36.                         // 將當前類路徑加入到類載入器中  
  37.                         method.invoke(classLoader, clazzPath.toURI().toURL());  
  38.                     } finally {  
  39.                         method.setAccessible(accessible);  
  40.                     }  
  41.                 }  
  42.                 // 檔案名稱  
  43.                 String className = subFile.getAbsolutePath();  
  44.                 className = className.substring(clazzPathLen, className.length() - 6);  
  45.                 className = className.replace(File.separatorChar, ‘.‘);  
  46.                 // 載入Class類  
  47.                 Class.forName(className);  
  48.                 LOG.debug("讀取應用程式類檔案[class={}]", className);  
  49.             }  
  50.         }  
  51.     }  
  52. }  

  完成上述兩步操作後,即可使用Class.forName來載入jar中或.class檔案包含的Java類了。

[轉載] Java中動態載入jar檔案和class檔案

聯繫我們

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