Thread.currentThread().getContextClassLoader()和Class.getClassLoader()區別

What is different between Thread.currentThread().getContextClassLoader() and Class.getClassLoader()?

From API document, the 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. 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. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources. For example, JNDI and JAXP used thread's ClassLoader. You had better to use thread's ClassLoader in your own code when your code need to deployed on J2EE container.

The 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. For example, Class.getResource() and Class.forName() will use the class loader of trhe current caller's class.

The Understanding Class.forName() by Ted Neward is excellent paper on ClassLoader.

DriverManager.getConnection is example:http://daizuan.iteye.com/blog/1138683
System.out.println(DriverManager.class.getClassLoader()); 
控制檯輸出null
代表DriverManager的classLoader是至關NB的bootstrap ClassLoader
而咱們本身寫的類通常都是由systemClassloader加載的。
若是在DriverManager直接class.forName("com.mysql.jdbc.ReplicationDriver"),就表示要讓bootstrap ClassLoader來加載jdk/lib目錄下的com.mysql.jdbc.ReplicationDriver,可能麼??明顯不在那裏,而是在classpath目錄下。
因此要這麼來class.forName("com.mysql.jdbc.ReplicationDriver",true, callerClassLoader)

另外若是getCallerClassLoader()返回了空,則會獲取當前線程上下文的classLoader .mysql

相關文章
相關標籤/搜索