/**
* 自定义ClassLoader
*
* @author leizhimin 2009-7-29 22:05:48
*/
public class MyClassLoader {
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
URL url = new URL("file:/E://projects//testScanner//out//production//testScanner");
ClassLoader myloader = new URLClassLoader(new URL[]{url});
Class c = myloader.loadClass("test.Test3");
System.out.println("----------");
Test3 t3 = (Test3) c.newInstance();
}
}
public class Test3 {
static {
System.out.println("Test3的静态初始化块执行了!");
}
}
运行后:
----------
Test3的静态初始化块执行了!
Process finished with exit code 0
可以看出自定义了ClassLoader myloader = new URLClassLoader(new URL[]{url});已经成功将类Test3加载到内存了,并通过默认构造方法构造了对象Test3 t3 = (Test3) c.newInstance();
有关ClassLoader还有很重要一点:
同一个ClassLoader加载的类文件,只有一个Class实例。但是,如果同一个类文件被不同的ClassLoader载入,则会有两份不同的ClassLoader实例(前提是着两个类加载器不能用相同的父类加载器)