gpt4 book ai didi

java - Thread.currentThread() 类加载器和普通类加载器的区别

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:21 24 4
gpt4 key购买 nike

你能告诉我 Thread.currentThread().getContextClassLoader()TestServlet.class.getClassLoader() 之间的区别是什么,不要将其标记为重复和也请解释并提供示例何时使用这些

Java 文件:

package com.jar.test;

public class TestServlet {
public static void main(String args[]) {
ClassLoader cls = TestServlet.class.getClassLoader().loadClass(
"com.jar.test.TestServlet");
ClassLoader cls = Thread.currentThread().getContextClassLoader()
.loadClass("com.jar.test.TestServlet");
}
}

最佳答案

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. If not set, 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.

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.


简而言之:

Thread.currentThread().getContextClassLoader()是用 setContextClassLoader(ClassLoader cl) 设置的线程上下文的 ClassLoader .假设您有一个具有 ClassLoader 层次结构的复杂 java 应用程序(例如应用程序服务器),并且您希望当前线程从一个特定的 ClassLoader 中加载类或资源对于这个层次结构,您可以通过简单地将线程的上下文 ClassLoader 设置为这个特定的 ClassLoader 来实现。

Class#getClassLoader()只是 ClassLoader,您的 Class 实例已从中加载。

关于java - Thread.currentThread() 类加载器和普通类加载器的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303433/

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