区别:Thread.currentThread().getContextClassLoader() and Class.getClassLoader()

本文深入探讨了Java中Thread.currentThread().getContextClassLoader()与Class.getClassLoader()方法的区别,解释了上下文类加载器与类加载器的概念,并通过实例展示了它们在实际应用中的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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.

=======================================================================

查找路径路径不同

1、classpath根开始查找:Thread.currentThread().getContextClassLoader().getResource()

从当前类的目录下开始查找,要找根路径下的内容,必须以/为开头:

ConfigManager.class.getResource("/biz/unicorn-client.properties");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值