前言
面试Java时,一个较为常见的问题是——“能否加载自己的String类?”
那到底能不能呢?本文就带你一探究竟。(想知道答案的小伙伴可以直接跳到文章末尾~)
预备知识
- 虚拟机类加载机制
- 双亲委派模型
- 定义自己的类加载器
以上内容是本文的预备知识,《深入理解Java虚拟机》这本书以及网上的很多文章都已经讲的很清楚了,还不清楚的读者可以自行查阅,本文就不再赘述。
加载自己的String类
首先,我们需要知道,双亲委派模型并不是一个强制性的约束条件,而只是Java设计者推荐给开发者的类加载器实现方式。
双亲委派模型的实现位于ClassLoader类的loadClass方法中,源码如下:
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
PerfCounter.getParentDelegationTime().addTime(t1 - t0);
PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
PerfCounter.getFindClasses().increment();
}
}
if (resolve) {