Java 動態載入jar和class檔案執行個體解析,jarclass

來源:互聯網
上載者:User

Java 動態載入jar和class檔案執行個體解析,jarclass

本文研究的主要是Java 動態載入jar和class檔案的相關內容,具體如下。

JAVA中類檔案載入是動態。也就是說當我們用到的時候才會去載入,如果不用的話,就不會去載入我們的類。

JAVA為我們提供了兩種動態機制。第一種是隱式機制。第二種是顯示機制。如下:

兩種方法:

  • 隱式機制 :new一個對象 + 調用類的靜態方法
  • 顯式機制 :由 java.lang.Class的forName()方法載入
    由 java.lang.ClassLoader的loadClass()方法載入
1、Class.forName

Class.forName()方法具有兩個形式:

  • public static Class forName(String className)
  • public static Class forName(String className, boolean initialize,ClassLoader loader)
參數說明:
  • className - 所需類的完全限定名 (必須包含包名,否則出錯!)
  • initialize - 是否必須初始化類 (靜態代碼塊的初始化)
  • loader - 用於載入類的類載入器

調用只有一個參數的forName()方法等效於 Class.forName(className, true, loader)。

這兩個方法,最後都要串連到原生方法forName0().

而三個參數的forName(),最後調用的是: forName0(name, initialize, loader);

不管使用的是new 來執行個體化某個類、或是使用只有一個參數的Class.forName()方法,內部都隱含了“載入類 + 運行靜態代碼塊”的步驟。

而使用具有三個參數的Class.forName()方法時,如果第二個參數為false,那麼類載入器只會載入類,而不會初始化靜態代碼塊,只有當執行個體化這個類的時候,靜態代碼塊才會被初始化,靜態代碼塊是在類第一次執行個體化的時候才初始化的。

2、java.lang.ClassLoader

ClassLoader就是用來Load Class的,當一個Class被載入的時候,這個Class所引用到的所有Class也會被載入,而且這種載入是遞迴的,也就是說,如果A引用到B,B 引用到C,那麼當A被載入的時候,B也會被載入,而B被載入的時候,C也會載入。如此遞迴直到所有需要的Class都載入好。

package com.demo.test;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.MalformedURLException;import java.net.URL;import java.net.URLClassLoader;public class DynamicLoadDemo {enum FileType {JAR, CLASS, OTHER}static class MyClassLoader extends ClassLoader {public synchronized Class<?> loadClass(String name, File file) throws FileNotFoundException {Class<?> cls = findLoadedClass(name);if(cls != null) {return cls;}FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;try {while (true) {len = fis.read(buffer);if (len == -1) {break;}baos.write(buffer, 0, len);}//FileInputStream的flush是空操作,因為flush的作用是把緩衝中的東西寫入實體(硬碟或網路流)中,這裡沒有這種必要所以為空白//baos.flush();byte[] data = baos.toByteArray();return defineClass(null, data, 0, data.length);}catch (IOException e) {e.printStackTrace();}finally {try {baos.close();}catch (IOException e) {e.printStackTrace();}try {fis.close();}catch (IOException e) {e.printStackTrace();}}return null;}}public static void main(String[] args) {String className = "com.demo.test.HelloWorld";String paths[] = { "HelloWorld.jar", "HelloWorld.class" };for (String path : paths) {String lowerPath = path.toLowerCase();FileType fileType = FileType.OTHER;if (lowerPath.endsWith(".jar") || lowerPath.endsWith(".zip")) {fileType = FileType.JAR;} else if (lowerPath.endsWith(".class")) {fileType = FileType.CLASS;}if (fileType == FileType.OTHER) {return;}File file = new File(path);if (!file.exists()) {return;}try {URL url = file.toURI().toURL();System.out.println(url.toString());Class<?> cls = null;switch (fileType) {case JAR:          URLClassLoader classLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());cls = classLoader.loadClass(className);break;case CLASS:          MyClassLoader myClassLoader = new MyClassLoader();cls = myClassLoader.loadClass(className, file);break;default:          break;}if (cls == null) {return;}// 執行個體變數Field field = cls.getDeclaredField("hello");if (!field.isAccessible()) {field.setAccessible(true);}System.out.println(field.get(cls.newInstance()));// 調用靜態不帶參數方法Method staticMethod = cls.getDeclaredMethod("sayStaticHello", null);if (!staticMethod.isAccessible()) {staticMethod.setAccessible(true);}// 如果函數的傳回值是void,就會返回nullstaticMethod.invoke(cls, null);// 執行個體帶參數方法方法Method method = cls.getDeclaredMethod("say", String.class);if (!method.isAccessible()) {method.setAccessible(true);}Object ret = method.invoke(cls.newInstance(), "hello world");System.out.println(ret);}catch (MalformedURLException e) {e.printStackTrace();}catch (ClassNotFoundException e) {e.printStackTrace();}catch (NoSuchMethodException e) {e.printStackTrace();}catch (SecurityException e) {e.printStackTrace();}catch (IllegalAccessException e) {e.printStackTrace();}catch (IllegalArgumentException e) {e.printStackTrace();}catch (InvocationTargetException e) {e.printStackTrace();}catch (InstantiationException e) {e.printStackTrace();}catch (NoSuchFieldException e) {e.printStackTrace();}catch (FileNotFoundException e) {e.printStackTrace();}}}}

結果:

總結

以上就是本文關於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.