JVM、JRE、JDK
JVM:java虚拟机
JRE:java运行时环境
JDK:java开发环境
JRE = JVM + core lib
JDK = JRE + development kit
对象创建过程
1.loading
将二进制文件装入内存(双亲委派)
2.linking
1.1.verification
校验
1.2.preparation
将class文件的静态变量设置默认值
1.3.resoluton
将符号引用转换为内存地址
3.initalizing
调用构造方法
类加载流程
双亲委派机制
子加载器 -> 父加载器 -> 子加载器
类加载器使用双亲委派机制的原因:安全
类加载器范围
(以下来自Lancher)
bootstrapClassLoader加载路径:sun.boot.class.path
ExtensionClassLoader加载路径:java.ext.dirs
AppClassLoader加载路径:java.class.path
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;
}
}
类加载过程使用了模板设计模式,钩子函数是findClass(),子类实现findClass()
父类findClass()
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
findCache() -> parent.loadClass() -> findClass()
自定义类加载器
- extends ClassLoader
- overwrite findClass() -> defineClass(byte[] -> Class clazz)
- 加密