Test.java:
public class Test {
public static void main(String args[]) {
System.out.println(Test.class.getClassLoader());
Testlib tl = new Testlib();
tl.print();
}
}
Testlib.java:
public class Testlib {
public void print() {
System.out.println(
this.getClass().getClassLoader());
}
}
编译后目录如下:
Test.class
Test.class
Testlib.class
根据类装载机制,,当AppClassLoader要载入Test.class时,先请其parent, 也就是ExtClas
sLoader来载入, 而ExtClassLoader又请求其Parent, 即BootStrap Loader来载入Test.cl
ass, 由于
ap Loader找到了test.class,因此将它载入.接着在Test.class之内有载入Testlib.class的需求,由于Test.class
是由BootStrap Loader所载入,所以Testlib.class内定是由Bootstrap Loader根据其搜索
路径来寻找,但是因为Bootstrap Loader根本找不到Testlib.class, 而Bootstrap Loader
又没有parent, 所以无法载入Testlib.class. 故java Test后结果如下:
null
Exception in thread "main" java.lang.NoClassDefFoundError:Testlib at Test.main
但我把Test代码中的Test.class.getClassLoader()变为Thread.currentThread().getCon
textClassLoader()后第一行输出变成了AppClassLoader, 请问这是为什么?我查过JDK文档
,上面写得很清楚:
The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.
应该也是parent来load, 既然parent能找到,为什么这里是AppClassLoader来load?望指点
另外对于第一种情况,又没有什么办法能让Testlib.class被load?书上说是用Context Loader,不明白是何意