运行java运行某个类的main方法时,首先需要通过类加载器把主类加载到jvm
其中classLoader类加载过程有如下几步
加载 ==> 验证 ==> 准备 ==> 解析 ==> 初始化 ==> 使用 ==>卸载
在加载阶段会在内存中生成一个代表这个类的java.lang.Class对象,作为方法区这个类的各种数据的访问入口
类被加载到方法区后主要包含运行时常量池,类型信息,字段信息,方法信息,类加载器的引用,对应class实例的引用等信息
类加载的引用:这个类到类加载器实例的引用
对应class实例的引用:类加载器在加载类信息放到方法区中后,会创建一个对应Class类型的对象实例放到堆中
public class A {
static {
System.out.println("-----------load A--------------");
}
public A() {
System.out.println("----------initial A--------------");
}
}
public class B {
static {
System.out.println("-----------load B--------------");
}
public B() {
System.out.println("----------initial B--------------");
}
}
public class TestDynamicLoad {
static {
System.out.println("-----------TestDynamicLoad----------");
}
public static void main(String[] args) {
new A();
System.out.println("===============test==========");
B b = null;
}
}
-----------TestDynamicLoad----------
-----------load A--------------
----------initial A--------------
===============test==========
引导类加载器:负责加载支撑JVM运行的位于JRE的lib目录下的核心类库,比如rt.jar、charsets.jar等
扩展类加载器:负责加载支撑JVM运行的位于JRE的lib目录下的ext扩展目录中的JAR类包
应用程序类加载器:负责加载ClassPath路径下的类包,主要就是加载你自己写的那些类自定义加载器:负责加载用户自定义路径下的类包
public class TestJDKClassloader {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(DESKeyFactory.class.getClassLoader());
System.out.println(TestJDKClassloader.class.getClassLoader());
System.out.println();
ClassLoader appClassLoader = ClassLoader.getSystemClassLoader();
ClassLoader extClassLoader = appClassLoader.getParent();
ClassLoader bootstrapClassLoader = extClassLoader.getParent();
System.out.println("appClassLoader:" + appClassLoader);
System.out.println("extClassLoader:" + extClassLoader);
System.out.println("bootstrapClassLoader:" + bootstrapClassLoader);
System.out.println("bootstrapClassLoader加载以下文件");
URL[] urLs = Launcher.getBootstrapClassPath().getURLs();
for (URL urL : urLs) {
System.out.println(urL);
}
System.out.println("extClassLoader加载以下文件");
System.out.println(System.getProperty("java.ext.dirs"));
System.out.println("appClassLoader加载以下文件");
System.out.println(System.getProperty("java.class.path"));
}
}
null
sun.misc.Launcher$ExtClassLoader@12a3a380
sun.misc.Launcher$AppClassLoader@18b4aac2
appClassLoader:sun.misc.Launcher$AppClassLoader@18b4aac2
extClassLoader:sun.misc.Launcher$ExtClassLoader@12a3a380
bootstrapClassLoader:null
bootstrapClassLoader加载以下文件
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/resources.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/rt.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/sunrsasign.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/jsse.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/jce.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/charsets.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/lib/jfr.jar
file:/C:/Program%20Files/Java/jdk1.8.0_112/jre/classes
extClassLoader加载以下文件
C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext;C:\Windows\Sun\Java\lib\ext
appClassLoader加载以下文件
C:\Program Files\Java\jdk1.8.0_112\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_112\jre\lib\rt.jar;D:\workspace\example\target\classes;D:\idea2019\IntelliJ IDEA 2019.3.1\lib\idea_rt.jar
protected Class> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// 检查当前类加载器是否已经加载了该类
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();
// 都会调用UrlClassLoader的findClass方法在加载器路径里找到并加载该类
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;
}
}
例如:定义java.lang.String类 ,定义main方法并启动。
这个时候类加载器去加载,先会去AppClassLoader加载,没有加载过则会去ExtClassLoader加载最后委托BootStrapClassLoader加载 ,BootStrapClassLoader去加载去rt.jar包下去加载,结果找到了,加载成功了,这个类是jdk里的java.lang.String,但是在jdk里的String类是没有main方法的 所以启动报错.
全盘负责是指一个ClassLoader装载一个类时,除非显示的使用另外一个ClassLoder,该类所依赖的以及引用的类也由这个ClassLoader载入
自定义类加载器只需要继承java.lang.ClassLoader类,该类有两个核心方法,一个是loadClass(String,boolean),实现了双亲委派机制,还有一个方法是findClass,默认是空方法,所以我们自定义类加载器主要是重写findClass方法
public class MyClassLoader extends ClassLoader {
private String classPath;
public MyClassLoader(String classPath) {
this.classPath = classPath;
}
public MyClassLoader(ClassLoader parent, String classPath) {
super(parent);
this.classPath = classPath;
}
@Override
protected Class> findClass(String name) throws ClassNotFoundException {
try {
byte[] bytes = loadByte(name);
// name: 全类名 bytes:这个类文件的byte数组
return defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
throw new ClassNotFoundException();
}
}
@Override
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 (name.startsWith("com.zexiang")) {
c = findClass(name);
} else {
c = super.loadClass(name, false);
}
} 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;
}
}
private byte[] loadByte(String name) throws Exception {
name = name.replaceAll("\\.", "/");
FileInputStream fileInputStream = new FileInputStream(classPath + "/" + name + ".class");
int len = fileInputStream.available();
byte[] bytes = new byte[len];
fileInputStream.read(bytes);
fileInputStream.close();
return bytes;
}
}
public class MyClassLoaderTest {
private String name;
public static void main(String[] args) throws Excfeption {
MyClassLoader myClassLoader = new MyClassLoader("D://");
Class> aClass = myClassLoader.loadClass("com.zexiang.java.jvm.classloader.myclassloader.Process");
Object o = aClass.newInstance();
Method method = aClass.getDeclaredMethod("printProcessId", String.class);
Object invoke = method.invoke(o,"123");
System.out.println(aClass.getClassLoader().getClass().getName());
}
}
123
com.zexiang.java.jvm.classloader.myclassloader.MyClassLoader
tomcat 这种类加载机制违背了java 推荐的双亲委派模型了吗?答案是:违背了。 很显然,tomcat 不是这样实现,tomcat 为了实现隔离性,没有遵守这个约定,每个 webappClassLoader加载自己的目录下的class文件,不会传递给父类加载器,打破了双亲委 派机
为什么可以实现同一个类路径可以加载不同的类呢?
众所周知在自定义加载器中如果已经加载了类(类路径+类名),那么就不会委托上级加载,直接返回。
但是如果用的是不同的类加载器呢 ? 在A类在加载器中加载了Process类,但是在B类加载器中没有加载过,这个时候B类加载器也会去加载Process类,这样就可以做到类的隔离
public class MyDifferentClassLoaderTest {
private String name;
public static void main(String[] args) throws Exception {
MyClassLoader myClassLoader = new MyClassLoader("D://test");
Class> aClass = myClassLoader.loadClass("com.zexiang.java.jvm.classloader.myclassloader.Process");
Object o = aClass.newInstance();
Method method = aClass.getDeclaredMethod("printProcessId", String.class);
method.invoke(o,"123");
System.out.println(aClass.getClassLoader().getClass().getName());
MyClassLoader myClassLoader2 = new MyClassLoader("D://test1");
Class> aClass2 = myClassLoader2.loadClass("com.zexiang.java.jvm.classloader.myclassloader.Process");
Object o2 = aClass2.newInstance();
Method method2= aClass2.getDeclaredMethod("printProcessId", String.class);
method2.invoke(o2,"123");
System.out.println(aClass2.getClassLoader().getClass().getName());
}
}
123
com.zexiang.java.jvm.classloader.myclassloader.MyClassLoader
另外一个版本的123
com.zexiang.java.jvm.classloader.myclassloader.MyClassLoader