gpt4 book ai didi

java - 何时在 Web 应用程序中使用 Thread.currentThread().getContextClassLoader()

转载 作者:行者123 更新时间:2023-11-30 02:47:11 39 4
gpt4 key购买 nike

嗨,有人可以告诉我何时使用Thread.currentThread().getContextClassLoader()在网络应用程序中。请给我一些现实生活中的例子。请不要将其标记为重复问题(我的问题是何时使用 Thread.currentThread().getContextClassLoader() 并且不用于加载属性文件)。我浏览了很多网站,但没有得到正确的答案。

最佳答案

首先,请注意,此方法与 Java EE 无关,它是 Java SE 的方法,因此它不是本意的东西仅在 Web 应用程序中使用,但可能在任何 Java 应用程序中使用。

我们通常将此方法与Thread.currentThread().setContextClassLoader(ClassLoader)结合使用,以检查和/或更改调用线程的上下文ClassLoader

因此,通常假设您正在编写一个 Java 应用程序,该应用程序需要一个自定义 ClassLoader 来从最初不在类路径上的特定文件夹和/或 jar 文件加载类,您将使用这些更改上下文 ClassLoader 并恢复以前的 CL 的方法。这将允许您的代码访问以前无法从当前上下文 CL 访问的类,因为它们最初不在类路径上。

因此,您的代码如下所示:

// The previous context ClassLoader
final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
try {
// Set my custom ClassLoader to make my classes accessible
Thread.currentThread().setContextClassLoader(myCustomCL);
// Execute some code here that will be able to access to classes or resources from
// my specific folders and/or jar files

} finally {
// Restore the previous CL
Thread.currentThread().setContextClassLoader(contextCL);
}

关于java - 何时在 Web 应用程序中使用 Thread.currentThread().getContextClassLoader(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849690/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com