博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Thread.currentThread().getContextClassLoader()和Class.getClassLoader()区别
阅读量:6590 次
发布时间:2019-06-24

本文共 1940 字,大约阅读时间需要 6 分钟。

hot3.png

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 .

转载于:https://my.oschina.net/gavinjin/blog/800382

你可能感兴趣的文章
电子商务网站之购买欲望和购买目标
查看>>
js中判断 .html() 是否为空
查看>>
Linux性能测试 iostat命令
查看>>
Alpha 冲刺 (1/10)
查看>>
Web常见约定规范(精选)
查看>>
Spring.NET学习笔记
查看>>
HTML5 服务器推送事件(Server-sent Events)实战开发
查看>>
linux下PHP后台配置极光推送问题
查看>>
html基本介绍
查看>>
[转]特征选择与特征选择权重之区别
查看>>
c/c++内存机制(转)
查看>>
移动开发者大会第一日观感
查看>>
数制转化2
查看>>
Django + Uwsgi + Nginx 实现生产环境 项目部署
查看>>
02-CSS基础与进阶-day5_2018-09-03-20-20-37
查看>>
大数据之nutch
查看>>
52、多线程创建的三种方式对比
查看>>
数据结构化与保存
查看>>
IntelliJ IDEA工具的安装使用
查看>>
进程间通信
查看>>