四种:
- BootstrapClassLoader根加载器/引导加载器,不继承ClassLoader,负责
$JAVA_HOME/jre/lib
核心类的加载.- ExtClassLoader扩展类加载器。负责
$JAVA_HOME/jre/lib/ext
目录下的class加载- AppClassLoader系统类加载器,负责加载开发者实际项目中编写类。
- 自定义ClassLoader 需要重写
findClass()
方法,远程加载(本地/网络下载)类。
类加载机制-双亲委托机制
,什么是双亲委托机制,当查找一个类时,首先获取一个AppClassLoader
(ClassLoader.getSystemClassLoader())的实例,然后向上级层层请求,如果最上层处理不了,就下放到下级加载。一旦加载就不再往下传。
以下是实例。
- 首先,定义一个实体类
@Data
public class Order {
private String orderId;
}
- 验证AppClassLoader 双亲是ExtClassLoader
@Slf4j
public class LoaderDemo {
public static void main(String[] args) {
try {
loadClass();
loadParentClass();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void loadClass() throws ClassNotFoundException{
Class clazz = Class.forName("com.valor.practice.learn.loader.Order");
ClassLoader loader = clazz.getClassLoader();
log.info("My class loader: {}",loader.getClass().getSimpleName());
}
private static void loadParentClass() throws ClassNotFoundException{
Class clazz = Class.forName("com.valor.practice.learn.loader.Order");
ClassLoader classLoader = clazz.getClassLoader();
while(classLoader.getParent()!=null){
classLoader = classLoader.getParent();
log.info("Parent Class loader: {}",classLoader.getClass().getSimpleName());
}
}
打印结果:
My class loader: AppClassLoader
Parent Class loader: ExtClassLoader
从源码角度理解双亲委托
机制
打开 ClassLoader
里的 loadClass()
方法:
- 检查目标class是否曾经加载过,如果加载过则直接返回
- 如果没加载过,把加载请求传递给 parent 加载器去加载
- 如果 parent 加载器加载成功,则直接返回
- 如果 parent 未加载到,则自身调用 findClass() 方法进行寻找,并把寻找结果返回。
源码如下:
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
自定义加载器
代码如下:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
public class SelfDefineClassLoader extends ClassLoader{
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = downloadClass(name);
if (classData == null){
super.findClass(name);
}else {
return defineClass(name,classData,0,classData.length);
}
return null;
}
private byte[] downloadClass(String name) {
String path = ""+ File.separatorChar;
try {
URL url = new URL(path);
InputStream ins = url.openStream();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int read = 0;
while ((read = ins.read(buffer)) != -1) {
byteStream.write(buffer, 0, read);
}
return byteStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}