Java ClassLoader类加载机制(二)类加载器
2019-04-29 本文已影响4人
魏树鑫
1. 类加载的种类
- 启动类加载器,Bootstrap ClassLoader,最顶层的加载类,主要加载核心类库,%JRE_HOME%\lib下的rt.jar、resources.jar、charsets.jar和class等。另外需要注意的是可以通过启动jvm时指定-Xbootclasspath和路径来改变Bootstrap ClassLoader的加载目录。比如java -Xbootclasspath/a:path被指定的文件追加到默认的bootstrap路径中。我们可以打开我的电脑,在上面的目录下查看,
- 扩展类加载器,Extension ClassLoader,加载%JRE_HOME%\lib\ext,或者被java.ext.dirs系统变量指定的类;
- 应用程序类加载器,Application ClassLoader,加载ClassPath中的类库;通常我们通过Class.getClassLoader()所获得到的类加载器就是应用类加载器;
ClassLoader appClassLoader = ClassLoader.getSystemClassLoader();
- 自定义类加载器,通过继承ClassLoader实现,一般是加载我们的自定义类;
程序加载入口sun.misc.Launcher
package sun.misc;
/**
* This class is used by the system to launch the main application.
*/
public class Launcher {
private static URLStreamHandlerFactory factory = new Factory();
private static Launcher launcher = new Launcher();
private static String bootClassPath = System.getProperty("sun.boot.class.path");
public static Launcher getLauncher() {
return launcher;
}
private ClassLoader loader;
public Launcher() {
// Create the extension class loader
ClassLoader extcl;
try {
extcl = ExtClassLoader.getExtClassLoader();
} catch (IOException e) {
throw new InternalError("Could not create extension class loader", e);
}
// Now create the class loader to use to launch the application
try {
loader = AppClassLoader.getAppClassLoader(extcl);
} catch (IOException e) {
throw new InternalError("Could not create application class loader", e);
}
// Also set the context class loader for the primordial thread.
Thread.currentThread().setContextClassLoader(loader);
// Finally, install a security manager if requested
String s = System.getProperty("java.security.manager");
if (s != null) {
SecurityManager sm = null;
if ("".equals(s) || "default".equals(s)) {
sm = new java.lang.SecurityManager();
} else {
try {
sm = (SecurityManager)loader.loadClass(s).newInstance();
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
} catch (ClassCastException e) {
}
}
if (sm != null) {
System.setSecurityManager(sm);
} else {
throw new InternalError("Could not create SecurityManager: " + s);
}
}
}
}
可以发现
- 系统先拿个扩展类加载器
ExtClassLoader.getExtClassLoader()
,然后又拿个应用加载器AppClassLoader.getAppClassLoader(extcl)
,并且将ExtClassLoader设为AppClassLoader的父加载器; - 设置当前线程的ClassLoader,也就是说,系统的第一个线程的类加载器都由
AppClassLoader
来加载; -
最后再初始化个安全策略的Manager,用于在执行不安全或者敏感的操作时,进行安全校验;比如文件权限校验;
看一下Launcher中的各个类的关系:
Launcher与ClassLoader关系.png
可以发现所有的类加载器最终都是继承自ClassLoader,而AppClassLoader和ExClassLoader是Launcher的内部类。
2. 真正开始加载类,loaderClass方法
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;
}
}
双亲委派模型
- 可以发现加载时会先去找parentClassLoader,如果父加载器为空,则用BootStrapClassLoadder去加载,如果不为空,用parentClassLoader加载,而parentClassLoader调用到loaderClass时,依旧这样执行,类似于递归一样;
- 也能发现类加载器 Java 类如同其它的 Java 类一样,也是要由类加载器来加载的;除了启动类加载器,每个类都有其父类加载器(父子关系由组合(不是继承)来实现);
- 所谓双亲委派是指每次收到类加载请求时,先将请求委派给父类加载器完成(所有加载请求最终会委派到顶层的Bootstrap ClassLoader加载器中),如果父类加载器无法完成这个加载(该加载器的搜索范围中没有找到对应的类),子类尝试自己加载。
双亲委派好处
- 避免同一个类被多次加载;
- 每个加载器只能加载自己范围内的类;
3. 自定义ClassLoader
class NetworkClassLoader extends ClassLoader {
String host;
int port;
public Class findClass(String name) {
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name) {
// load the class data from the connection
}
}
4. 类加载决定对象是否相同
要判断两个类是否“相同”,前提是这两个类必须被同一个类加载器加载,否则这个两个类不“相同”。
这里指的“相同”,包括类的Class对象的equals()方法、isAssignableFrom()方法、isInstance()方法、instanceof关键字等判断出来的结果
public class ClassLoaderTest {
public static void main(String[] args) {
ClassLoader newClassLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
InputStream resourceAsStream = getClass().getResourceAsStream(fileName);
if (resourceAsStream == null) {
return super.loadClass(name);
}
byte[] bytes = new byte[resourceAsStream.available()];
int read = resourceAsStream.read(bytes);
resourceAsStream.close();
return defineClass(name, bytes, 0, read);
} catch (IOException e) {
e.printStackTrace();
}
return super.loadClass(name);
}
};
ClassLoader appClassLoader = ClassLoader.getSystemClassLoader();
ClassLoader parentClassLoader = ClassLoaderTest.class.getClassLoader().getParent();
try {
String className = "com.wei.sample.classloader.ClassLoaderTest";
Class<?> aClass = newClassLoader.loadClass(className);
System.out.println(aClass);
System.out.println(aClass.newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
System.out.println(ClassLoaderTest.class.getClassLoader().loadClass(className).newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
System.out.println(appClassLoader.loadClass(className).newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
//Console 输出
[Loaded com.wei.sample.classloader.ClassLoaderTest from file:../compileDebugJavaWithJavac/classes/]
[Loaded com.wei.sample.classloader.ClassLoaderTest$1 from file:../compileDebugJavaWithJavac/classes/]
[Loaded com.wei.sample.classloader.ClassLoaderTest from __JVM_DefineClass__]
class com.wei.sample.classloader.ClassLoaderTest
false
true
true