ClassLoader可以用來(lái)方便的加載資源文件. 但如果資源文件在jar包里,不可使用Thread.currentThread().getContextClassLoader()來(lái)加載.
方法: Thread.currentThread().getContextClassLoader();
Returns the context ClassLoader for this Thread. 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.
例如在Tomcat自己寫(xiě)的Servlet中,返回的ClassLoader如下,對(duì)應(yīng)的目錄是/WEB-INF/classes/:
WebappClassLoader
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@5c74c3aa所以如Hibernate, log4j, struts等把配置文件按規(guī)則取名,直接放在/WEB-INF/classes/目錄里,會(huì)被自動(dòng)的找到,而不需要做其他的配置。
而在普通的運(yùn)用程序中,即自己寫(xiě)的類(lèi)的ClassLoader: Test.class.getClassLoader().