ContextClassLoader浅析

来源:互联网 发布:有没有淘宝店铺转让的 编辑:程序博客网 时间:2024/05/29 13:21

Current ClassLoader

当前类所属的ClassLoader,在虚拟机中类之间引用,默认就是使用这个ClassLoader。另外,当你使用Class.forName(), Class.getResource()这几个不带ClassLoader参数的方法时,默认同样使用当前类的ClassLoader。你可以通过方法XX.class.GetClassLoader()获取。

Thread Context ClassLoader

每一个Thread都有一个相关联的Context ClassLoader(由native方法建立的除外),可以通过Thread.setContextClassLoader()方法设置。如果你没有主动设置,Thread默认集成Parent Thread的 Context ClassLoader(注意,是parent Thread 不是父类)。如果你整个应用中都没有对此作任何处理,那么 所有的Thread都会以System ClassLoader作为Context ClassLoader。知道这一点很重要,因为从web服务器,java企业服务器使用一些复杂而且精巧的ClassLoader结构去实现诸如JNDI、线程池和热部署等功能以来,这种简单的情况越发的少见了,一般都会使用特定的classloader来设置thread context classLoader。

Thread.currentThread().getContextClassLoader()的意义:

父Classloader可以使用当前线程Thread.currentthread().getContextLoader()中指定的classloader中加载的类。颠覆了父ClassLoader不能使用子Classloader或者是其它没有直接父子关系的Classloader中加载的类这种情况。这个就是Context Class Loader的意义。

使用区别:

Thread Context ClassLoader多运用与框架中,因为它可以摆脱传统类加载委托机制,使框架能够使用通过不同类加载器加载的类对象。

Current ClassLoader多与业务相关,这些业务多处于同一模块中,使用相同的类加载器加载。

Q&A:

Q:

What is the difference between a thread's context class loader and a normal classloader? That is, ifThread.currentThread().getContextClassLoader() and getClass().getClassLoader()return different class loader objects, which one will be used?

A:

Each class will use it's own classloader to load other classes. So if ClassA.class referencesClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or it's parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on it's own classloader.

原创粉丝点击