打个简单的比方,你一个 WEB 程序,发布到 Tomcat 里面运行。
首先是执行 Tomcat org.apache.catalina.startup.Bootstrap 类,这时候的类加载器是 ClassLoader.getSystemClassLoader ()。
而我们后面的 WEB 程序,里面的 jar、resources 都是由 Tomcat 内部来加载的,所以你在代码中动态加载 jar、资源文件的时候,首先应该是使用 Thread.currentThread ().getContextClassLoader ()。如果你使用 Test.class.getClassLoader (),可能会导致和当前线程所运行的类加载器不一致(因为 Java 天生的多线程)。
Test.class.getClassLoader () 一般用在 getResource,因为你想要获取某个资源文件的时候,这个资源文件的位置是相对固定的。
java 的类加载机制(jvm 规范)是委托模型,简单的说,如果一个类加载器想要加载一个类,首先它会委托给它的 parent 去加载,如果它的所有 parent 都没有成功的加载那么它才会自己亲自来,有点儿像儿子使唤老子的感觉。
如果你使用 Test.class.getClassLoader (),可能会导致和当前线程所运行的类加载器不一致 :Class.getClassLoader()
returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
Java 路径
Java 中使用的路径,分为两种:绝对路径和相对路径。具体而言,又分为四种:
一、URI 形式的绝对资源路径
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b
URL 是 URI 的特例。URL 的前缀