Java规范中的类加载机制使用了双亲委托机制。
用户自定义的ClassLoader可继承java.lang.ClassLoader,重写下面的方法。该种方法是Java1.2后推荐的作法。
/**
* Finds the class with the specified <a href="#name">binary name</a>.
* This method should be overridden by class loader implementations that
* follow the delegation model for loading classes, and will be invoked by
* the {@link #loadClass <tt>loadClass</tt>} method after checking the
* parent class loader for the requested class. The default implementation
* throws a <tt>ClassNotFoundException</tt>. </p>
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @since 1.2
*/
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
另一个值得介绍的是ContextClassLoader,通过调用Thread.currentThread().getContextClassLoader();线程在创建时,可设置。
主要用于API的提供者,在无法确定使用哪个具体实现者时使用,比如JDK提供了一些Java API接口,用户根据自身需要给予实现,那JDK的代码中
如何加载实现类呢,本身加载java核心包是classloader在classloader的树形层次结构中处于很高的层次,按照正常的双亲加载机制,无法完成加载,
现在好了通过Thread传递下加载器即能解决这个问题。
如果现在有个文件目录下的有一堆jar包,而又两个jar包用包含着拥有相同完全限定名称的类,这算jar包冲突吗?
这不一定了,看应用的classloader加载这些类的机制了,现在搞两个URLClassLoader分别对应这个两个jar包的路径分别加载jar包中的类,只要这两类的对象不要错误的进行类型转换就OK了。