一、什么是ClassLoader
顾名思义,即是类加载器,具体作用就是将.class
文件加载到JVM虚拟机中去,程序就可以正确运行了。
二、认识.class文件
Java是解释性语言,编写的代码都是.java
文件,需要经过compile(编译)成.class
文件才能运行。拿入门Hello World来讲:
HelloWorld.java
public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
不能直接运行,需要执行javac HelloWorld.java
生成.class
文件;
HelloWorld.class
cafe babe 0000 0034 001d 0a00 0600 0f09
0010 0011 0800 120a 0013 0014 0700 1507
0016 0100 063c 696e 6974 3e01 0003 2829
... ...
.class
文件是字节码文件,加载到JVM中可以直接运行。换句话说,其他语言例如C编写的程序正确转换为.class
文件后,JVM也是能识别运行的。
三、初探ClassLoader
测试程序:
public class ClassLoaderDemo {
public static void main(String[] args) {
System.out.println(ClassLoaderDemo.class.getClassLoader());
System.out.println(String.class.getClassLoader());
}
}
输出:
sun.misc.Launcher$AppClassLoader@18b4aac2
null
说明这个类是经过AppClassLoader加载到JVM中的,顺便观察下继承图:
疑问:但是为什么String的类加载器是null??
四、Java提供的ClassLoader
- Bootstrap ClassLoader:最顶层的加载类,主要加载核心类库,%JRE_HOME%\lib下的rt.jar、resources.jar、charsets.jar和class等;
- Extention ClassLoader:扩展的类加载器,加载目录%JRE_HOME%\lib\ext目录下的jar包和class文件;
- Appclass Loader:也称为SystemAppClass,加载当前应用的classpath的所有类;
需要查看上述之间的联系,可以查看JVM的入口sun.misc.Launcher
,源码太长,精简后:
public class Launcher {
private static String bootClassPath = System.getProperty("sun.boot.class.path");
private static Launcher launcher = new Launcher();
public Launcher() {
Launcher.ExtClassLoader var1= Launcher.ExtClassLoader.getExtClassLoader();
this.loader = Launcher.AppClassLoader.getAppClassLoader(var1);
Thread.currentThread().setContextClassLoader(this.loader);
}
}
Launcher的构造方法中初始化了ExtClassLoader和AppClassLoader,但是不见BootstrapClassLoader,只有一个系统环境变量,查看sun.boot.class.path
;
sun.boot.class.path:
D:\developer\Java\jdk1.8\jre\lib\resources.jar;
D:\developer\Java\jdk1.8\jre\lib\rt.jar;
D:\developer\Java\jdk1.8\jre\lib\sunrsasign.jar;
D:\developer\Java\jdk1.8\jre\lib\jsse.jar;
D:\developer\Java\jdk1.8\jre\lib\jce.jar;
D:\developer\Java\jdk1.8\jre\lib\charsets.jar;
D:\developer\Java\jdk1.8\jre\lib\jfr.jar;
D:\developer\Java\jdk1.8\jre\classes
顺着这个配置文件,分别查看ExtClassLoader和AppClassLoader的源码,可以发现都有加载路径的配置,java.ext.dirs
和java.class.path
;
java.ext.dirs:
D:\developer\Java\jdk1.8\jre\lib\ext;
C:\Windows\Sun\Java\lib\ext
java.class.path:
D:\developer\Java\jdk1.8\jre\lib\charsets.jar;
D:\developer\Java\jdk1.8\jre\lib\deploy.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\access-bridge-64.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\cldrdata.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\dnsns.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\jaccess.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\jfxrt.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\localedata.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\nashorn.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\sunec.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\sunjce_provider.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\sunmscapi.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\sunpkcs11.jar;
D:\developer\Java\jdk1.8\jre\lib\ext\zipfs.jar;
D:\developer\Java\jdk1.8\jre\lib\javaws.jar;
D:\developer\Java\jdk1.8\jre\lib\jce.jar;
D:\developer\Java\jdk1.8\jre\lib\jfr.jar;
D:\developer\Java\jdk1.8\jre\lib\jfxswt.jar;
D:\developer\Java\jdk1.8\jre\lib\jsse.jar;
D:\developer\Java\jdk1.8\jre\lib\management-agent.jar;
D:\developer\Java\jdk1.8\jre\lib\plugin.jar;
D:\developer\Java\jdk1.8\jre\lib\resources.jar;
D:\developer\Java\jdk1.8\jre\lib\rt.jar;
D:\idea_work\ClassLoaderDemo\out\production\ClassLoaderDemo;
D:\developer\IntelliJ IDEA 2017.3\lib\idea_rt.jar
AppClassLoader的父加载器是ExtClassLoader,而ExtClassLoader的父加载器是BootstrapClassLoader。
注:父加载器不是父类,不能通过getParent()判定。
疑点:AppClassLoader getParent()是ExtClassLoader?
getParent()位于ClassLoader类下,直接返回私有变量parent,那么这个parent只有在ClassLoader的构造方法中初始化。回到Launcher源码this.loader = Launcher.AppClassLoader.getAppClassLoader(var1);
,再去查看getAppClassLoader便一目了然了。
那么ExtClassLoader为什么没有传入BootstrapClassLoader作为parent参数呢?Bootstrap ClassLoader是C/C++编写的,它本身是虚拟机的一部分,所以它并不是一个JAVA类,也就是无法在java代码中获取它的引用,这便解释上面String的加载器为什么是null。
五、双亲委托
JVM加载一个class时先查看是否已经加载过,没有则通过父加载器,然后递归下去,直到BootstrapClassLoader,如果BootstrapClassloader找到了,直接返回,如果没有找到,则一级一级返回(查看规定加载路径),最后到达自身去查找这些对象。这种机制就叫做双亲委托。
好处是:
- 避免重复加载
A和B都需要加载X,各自加载就会导致X加载了两次,JVM中出现两份X的字节码; - 防止恶意加载
编写恶意类java.lang.Object,自定义加载替换系统原生类;
按需查看ClassLoader下的loadClass方法(精简);
Class> c = findLoadedClass(name);
if (c == null) {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
}
也很好的印证了上面双亲委托模型,首先从缓存找,然后根据parent是否为null(BootstrapClassLoader)向上委托加载。
双亲委托只是JVM的规范,是可以通过在自定义ClassLoader时重写loadClass方法打破的。
六、自定义ClassLoader
首先想到的是继承ClassLoader重写loadClass(),那么可以这样写;
import java.io.*;
public class CustomClassLoader extends ClassLoader {
private static final String DRIVER = "D:\\idea_work\\ClassLoaderDemo\\classes";
private static final String FILE_TYEP = ".class";
@Override
public Class> loadClass(String name) {
byte[] data = loadClassData(name);
return defineClass(name, data, 0, data.length);
}
private byte[] loadClassData(String name) {
FileInputStream fis;
byte[] data = null;
try {
File file = new File(DRIVER, name + FILE_TYEP);
fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = fis.read()) != -1) {
baos.write(ch);
}
data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
- 指定自定义加载class文件的路径;
- 根据class名称解析获取对应的字节流数组;
- 重写loadClass()采用defineClass返回需要的Class类;
编写测试Main程序;
public class ClassLoaderDemo {
public static void main(String[] args) {
CustomClassLoader loader = new CustomClassLoader();
try {
Class c1 = loader.loadClass("Cat");
Object object = c1.newInstance();
System.out.println(object);
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
然后我们将编译后的Cat.class文件放在上述指定的目录下,执行会发现报错;
java.io.FileNotFoundException: D:\idea_work\ClassLoaderDemo\classes\java.lang.Object.class (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.(FileInputStream.java:138)
at CustomClassLoader.loadClassData(CustomClassLoader.java:28)
at CustomClassLoader.loadClass(CustomClassLoader.java:11)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at CustomClassLoader.loadClass(CustomClassLoader.java:12)
at ClassLoaderDemo.main(ClassLoaderDemo.java:6)
Exception in thread "main" java.lang.NullPointerException
at CustomClassLoader.loadClass(CustomClassLoader.java:12)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at CustomClassLoader.loadClass(CustomClassLoader.java:12)
at ClassLoaderDemo.main(ClassLoaderDemo.java:6)
可以发现,通过某类加载器加载的类,所拥有的成员变量同样是该类加载器加载。
有两种解决方案:
- 在loadClass()方法中增加判断,当加载class文件不存在即调用super.loadClass(name);
- 重写findClass()方法,实现过程不变,前提是自定义加载class文件的路径不在三大加载器加载路径中(推荐);
可以看到ClassLoader源码中有这个方法;
/**
* Finds the class with the specified binary name.
* 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 loadClass} method after checking the
* parent class loader for the requested class. The default implementation
* throws a ClassNotFoundException.
*
* @param name
* The binary name of the class
*
* @return The resulting Class object
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @since 1.2
*/
protected Class> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
默认抛出异常,自定义ClassLoader一般都需要重写该方法;
import java.io.*;
public class CustomClassLoader extends ClassLoader {
private static final String DRIVER = "D:\\idea_work\\ClassLoaderDemo\\classes";
private static final String FILE_TYEP = ".class";
@Override
public Class findClass(String name) {
byte[] data = loadClassData(name);
return defineClass(name, data, 0, data.length);
}
private byte[] loadClassData(String name) {
FileInputStream fis;
byte[] data = null;
try {
File file = new File(DRIVER, name + FILE_TYEP);
System.out.println(file.getAbsolutePath());
fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = fis.read()) != -1) {
baos.write(ch);
}
data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
再次执行Main程序正常输出。
疑问:可以编写java.lang.xxx,自定义替换加载?
编写java.lang.String类:
package java.lang;
public class String {
public static void main(String[] args) {
System.out.println("String");
}
}
运行打印错误信息:
错误: 在类 java.lang.String 中找不到 main 方法, 请将 main 方法定义为:
public static void main(String[] args)
否则 JavaFX 应用程序类必须扩展javafx.application.Application
根据双亲委托模型String早已在BootstrapClassLoader中加载过原生的,所以这里会提示找不到main方法;
编写java.lang.Test类:
package java.lang;
public class Test {
public static void main(String[] args) {
System.out.println("Test");
}
}
运行打印错误信息:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:662)
at java.lang.ClassLoader.defineClass(ClassLoader.java:761)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)
应该是由于Java的安全机制禁止自己命名包名java.lang的,查看ClassLoader源码看到有个preDefineClass方法:
/* Determine protection domain, and check that:
- not define java.* class,
- signer of this class matches signers for the rest of the classes in
package.
*/
private ProtectionDomain preDefineClass(String name,
ProtectionDomain pd)
{
if (!checkName(name))
throw new NoClassDefFoundError("IllegalName: " + name);
// Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
// relies on the fact that spoofing is impossible if a class has a name
// of the form "java.*"
if ((name != null) && name.startsWith("java.")) {
throw new SecurityException
("Prohibited package name: " +
name.substring(0, name.lastIndexOf('.')));
}
if (pd == null) {
pd = defaultDomain;
}
if (name != null) checkCerts(name, pd.getCodeSource());
return pd;
}
这个是在defineClass也就是将class文件字节流数组转换为Class对象时预处理过程,并且是private私有,不允许子类进行修改,因而编写java开头的包名加载都会受到限制。
七、参考文章
- 一看你就懂,超详细java中的ClassLoader详解