ClassLoader对jar的一个处理方式
/**
* @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方法呢,
怪了.
* @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方法呢,
怪了.