Thread.getContextClassLoader与Thread.getClassLoader()区别
在閱讀spring boot啟動(dòng)時(shí)候的源碼中,發(fā)現(xiàn)獲取classLoader使用的是getContextClassLoader于是乎產(chǎn)生了疑問(wèn),這種獲取ClassLoader的方式與我們最常見(jiàn)的通過(guò)Class.getClassLoader二者有什么區(qū)別?都是在什么場(chǎng)景下使用呢?
首先來(lái)看看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.
主要的意思是getClassLoader()返回該類(lèi)的類(lèi)加載器,如果是bootstrap加載器加載的類(lèi)返回Null,這種機(jī)制主要是為了安全考慮bootstrap是用來(lái)加載jvm核心庫(kù)的加載器不允許暴露給用戶操作,可能會(huì)引起類(lèi)沖突的問(wèn)題。
再來(lái)看一下getContextClassLoader()方法的說(shuō)明:
Sets the context ClassLoader for this Thread. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader, through getContextClassLoader, to code running in the thread when loading classes and resources.
這個(gè)方法返回叫線程上下文類(lèi)加載器。這個(gè)加載器的類(lèi)型指定的工作交給了線程創(chuàng)建者,創(chuàng)建者在創(chuàng)建線程之后用對(duì)應(yīng)的setContextClassLoader()方法將適合的類(lèi)加載器設(shè)置到線程中,那么線程中的代碼就可以通過(guò)getContextClassLoader()獲取到這個(gè)類(lèi)加載器來(lái)加載類(lèi)或者資源。如果不設(shè)置默認(rèn)是系統(tǒng)類(lèi)加載器就是 app ClassLoader()。
那么這個(gè)getContextLoader()方法在什么場(chǎng)景下使用呢? 因?yàn)楹芏嗫蚣転榱俗鲱?lèi)的隔離會(huì)通過(guò)不同的ClassLoader來(lái)做類(lèi)的隔離。假設(shè)框架提供了一個(gè)可擴(kuò)展的服務(wù)接口這個(gè)接口的類(lèi)加載器是app ClassLoader,但是這個(gè)接口是現(xiàn)實(shí)則交給使用者來(lái)擴(kuò)展,那么實(shí)現(xiàn)類(lèi)很有可能被自定義的ClassLoader加載導(dǎo)致appClassLoader無(wú)法找到實(shí)現(xiàn)類(lèi)。如果在框架的層面希望能夠獲取到接口實(shí)現(xiàn)類(lèi)就需要將實(shí)現(xiàn)類(lèi)用getContextClassLoader獲得的ClassLoader來(lái)加載。
總之,getContextClassLoader是原有代理類(lèi)加載模式的一種補(bǔ)充。提供一種在子ClassLoader加載的類(lèi)中獲取父ClassLoader的實(shí)例來(lái)操作父加載器加載類(lèi)的方法。
總結(jié)
以上是生活随笔為你收集整理的Thread.getContextClassLoader与Thread.getClassLoader()区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 设计一个名为complex的类来表示复数
- 下一篇: 西南科技大学OJ题 进制转换问题0961