ClassLoader對jar的一個處理方式

來源:互聯網
上載者:User
/**

 * @author tom

 *

 * 這個類測試動態載入jar檔案中的類

 */

public class JarLoader

{

 private static void test(String[] args) throws Exception

 {

  Object obj =   new MyAppClassLoader("").loadClass("TestCCL").newInstance();

  System.out.println( "loaded? " + obj );

 }

 public static void main(String[] args)

 {

  try

  {

   test(args);

  }

  catch(Exception e)

  {

   e.printStackTrace();

  }

 }

}

public class MyAppClassLoader extends URLClassLoader

{

 String m_jarFile = "E:\\javaproject\\classloaderTest\\bin\\test.jar";

 public MyAppClassLoader(String jarFile)

 {   

  super(new URL[0]);

  if(jarFile != null && jarFile.length() > 0)

  {

   this.m_jarFile = jarFile;

  }

 }

 

 public Class loadClass(String name) throws ClassNotFoundException

 { 

  System.out.println("MyAppClassLoader loadClass!!");

  try

  {

   URL url = new java.io.File(m_jarFile).toURL();

   return new URLClassLoader(new URL[]{url}).loadClass(name);   

  }

  catch(Exception e)

  {

   e.printStackTrace();

  }

  return super.loadClass(name);

 }

}

public class TestCCL

{

 public TestCCL()

 {

  System.out.println("CCL Run!!!");

  //new BB();

  try

  {

   Class.forName("BB").newInstance();

   //new BB();

  }

  catch(Exception e)

  {

   e.printStackTrace();

  }

 }

 public static void main(String[] args)

 {

  

 }

}

public class BB

{

 public BB()

 {

  System.out.println("BB construct");

 }

}

打出來的結果是

MyAppClassLoader loadClass!!

CCL Run!!!

BB construct

loaded? TestCCL@93dee9

“CCL Run!!!”這句話為什麼只出現了一次呢,照理Class.forName("BB")是用了MyAppClassLoader 的,為什麼沒有到loadClass方法呢,

怪了.

聯繫我們

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