1.对于任意一个类,都需要由加载它的类加载器和全类名同确立其在虚拟机中的唯一性
___________________________________________________
| 启动类加载器 |
| Bootstrap ClassLoader |
| /|\_________________________|_____
| | | \
| 扩展类加载器 | \
| Extension ClassLoader | \ 子类加载器委派父类加载器加载
| /|\_________________________|________\ 父类加载器不加载时,
| | | / 子类加载器才会加载
| 应用程序类加载器 | /
| Application ClassLoader | /
| / /|\ \___________|_____/
| / | \ |
| 自定义类加载器 自定义类加载器 ...... |
| Custom ClassLoader Custom ClassLoader |
|___________________________________________________|
2.四类加载器
|
|-启动类加载器 :加载$JAVA_HOME中jre/lib/rt.jar里所有的class,加载System.getProperty(“sun.boot.class.path”)所指定的路径或jar
|-扩展类加载器 :加载java平台中扩展功能的一些jar包,包括$JAVA_HOME中jre/lib/ *.jar或-Djava.ext.dirs指定目录下的jar包。
| 加载System.getProperty(“java.ext.dirs”)所指定的路径或jar。
|-应用程序类加载器:载classpath中指定的jar包及目录中class
|-自定义类加载器 :应用程序根据自身需要自定义的ClassLoader,如tomcat、jboss都会根据j2ee规范自行实现。
3.源码(自定义类加载器需继承ClassLoader类,重写findClass方法、loadClass方法)
public abstract class ClassLoader {
private final ClassLoader parent;
...
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
...
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);// First, check if the class has already been loaded
if (c == null) {
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
}
if (c == null) {
c = findClass(name);// If still not found, then invoke findClass in order to find the class.
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
...
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
...
}