ClassLoader可以用來方便的加載資源文件. 但如果資源文件在jar包里,不可使用Thread.currentThread().getContextClassLoader()來加載.
方法: 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自己寫的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)用程序中,即自己寫的類的ClassLoader: Test.class.getClassLoader().